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?

Vinod
  • 925
  • 8
  • 9

1 Answers1

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
Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78