Search code examples
c++c++11templatesstatic-variables

error: ‘SIZE’ cannot appear in a constant-expression when using template< class T, int MAX_SIZE >


I am getting a compilation error:

HuffTree.cpp:43:20: error: ‘SIZE’ cannot appear in a constant-expression
  PQueue<HuffNode*, SIZE>;

where the involved lines are:

void HuffTree::buildTree(char * chs, int * freqs, int size )
{
static const int SIZE = size;
PQueue<HuffNode*, SIZE>;

I've tried all different types for "SIZE"

PQueue<HuffNode*, size>; // From the method parameter
static const int SIZE = static_cast<int>(size);

etc. But the only the following compiles:

PQueue<HuffNode*, 10>; // Or any other random int

I also get the related error:

HuffTree.cpp:43:24: error: template argument 2 is invalid
PQueue<HuffNode*, SIZE>;

PQueue is a template class accepting:

template< class T, int MAX_SIZE >
PQueue(T* items, int size);

What type does 'size' need to be for the argument to be accepted?
Using c++11


Solution

  • The problem is that

    PQueue<HuffNode*, SIZE>;
    

    is a type and require a SIZE known at compile time.

    If you declare SIZE with a value known compile time, as in

    PQueue<HuffNode*, 10>;
    

    or also in

    static const int SIZE = 10;
    PQueue<HuffNode*, SIZE>;
    

    it should works.

    But if SIZE depend from a value, size, known only run-time (the input value of a function method is considered to be known runtime), the compiler can't known SIZE compile time.

    Addendum: you're using C++11; so try using constexpr instead of const

    static constexpr int SIZE = 10;