1
template<typename T, typename C = vector<T>>
class stack{
    ...
    friend class stack_array;
};

template<typename T, typename C = vector<T>, typename K = stack<T,C>>
class stack_array{
     ...
     static const size_t max_elem;
     array<K, max_elem> store;
     ...
};

template<typename T, typename C = vector<T>, typename K = stack<T,C>>
const size_t stack_array<T,C,K>::max_elem = 10;

I get the following compilation error for the above:

error: the value of ‘stack_array<T, C, K>::max_elem’ is not usable in a constant expression
array<K, max_elem> store;
                ^
note: ‘stack_array<T, C, K>::max_elem’ was not initialized with a constant expression
static const size_t max_elem;

I presume this error occurs since the static const variable max_elem is initialized after the template class definition. Is this understanding correct? Is there a way to resolve this error without necessarily changing the current usage of max_elem?

1 Answer 1

1

I 'd say to initialize the static member right in place.

static const size_t max_elem = 10;

More here.

Constant static members If a static data member of integral or enumeration type is declared const (and not volatile), it can be initialized with an initializer in which every expression is a constant expression, right inside the class definition:

struct X {
     const static int n = 1;
     const static int m{2}; // since C++11
     const static int k; }; 

     const int X::k = 3; // Only this needs to be defined
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.