我有以下类,我需要在声明时有两个常量。
template <int PAGE_DIV_SIZE, int BUFFERS_NUM>
class BufferPool {
//...
}
和 这是一个使用它的测试代码
void testBufferPool(const int pageDivSize, const int bufferNum){
// other code and declaration
BufferPool <pageDivSize, bufferNum> bufferPool(catalog, devNum, hostCapacityVec, devCapacityVec);
}
我收到以下错误:
error: ‘pageDivSize’ is not a constant expression
BufferPoolTest.cpp:26:39: note: in template argument for type ‘int’
BufferPoolTest.cpp:26:39: error: ‘bufferNum’ is not a constant expression
BufferPoolTest.cpp:26:39: note: in template argument for type ‘int’
BufferPoolTest.cpp:26:51: error: invalid type in declaration before ‘(’ token
BufferPoolTest.cpp:26:100: error: expression list treated as compound expression in initializer [-fpermissive]
BufferPoolTest.cpp:26:100: error: cannot convert ‘std::vector<long unsigned int>’ to ‘int’ in initialization
答案 0 :(得分:2)
为了实例化模板,编译器必须在编译时知道所有模板参数。在编译时无法找出pageDivSize和bufferNum的值。因此模板参数不应该是常量变量,而应该是常量表达式。
http://en.cppreference.com/w/cpp/language/constant_expression