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

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

我遇到编译错误:

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

其中涉及的行是:

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

我已经为“SIZE”尝试了所有不同的类型

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

等但只有以下编译:

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

我也收到相关错误:

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

PQueue 是一个模板 class 接受:

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

要接受参数,“size”需要什么类型?
使用 c++11

您每次输入成员时都试图将 size 分配给 static const 变量 SIZE。你必须在创建时给SIZE一个值一次,比如static const int SIZE = 10;。我建议在您的成员之外声明它:

const int MAX_SIZE = 10;

// ...

void HuffTree::buildTree(char * chs, int * freqs, int size )
{
    HuffNode* n = new HuffNode(/* args */);
    PQueue<HuffNode, MAX_SIZE> queue(n, size); // HuffNode in template, not HuffNode*

}

问题在于

PQueue<HuffNode*, SIZE>;

是一种类型,需要 SIZE 在编译时已知。

如果您声明 SIZE 的值是编译时已知的,如

PQueue<HuffNode*, 10>;

或也在

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

应该可以。

但是如果 SIZE 依赖于一个值,size,只知道 运行 时间(函数方法的输入值被认为是已知的 运行时间),编译器无法知道 SIZE 编译时间。

附录:您使用的是 C++11;所以尝试使用 constexpr 而不是 const

static constexpr int SIZE = 10;