template < int >
class CAT
{};
int main()
{
int i=10;
CAT<(const int)i> cat;
return 0; //here I got error: ‘i’ cannot appear in a constant-expression
}
甚至
int i=10;
const int j=i;
CAT<j> cat; //this still can not work
但我已经将 i 转换为 const int,为什么编译器仍然报错?
我的平台是ubuntu,gcc版本4.4.3
谢谢,
==============
感谢大家的意见,但在某些情况下,我需要一个非常量变量,
例如:
//alloperations.h
enum OPERATIONS
{
GETPAGE_FROM_WEBSITE1,
GETPAGE_FROM_WEBSITE2,
....
};
template< OPERATIONS op >
class CHandlerPara
{
static string parameters1;
static string parameters2;
....
static void resultHandler();
};
//for different operations,we need a different parameter, to achieve this
//we specified parameters inside CHandler, for example
template<>
string CHandlerPara< GETPAGE_FROM_WEBSITE1 >::parameters1("&userid=?&info=?..")
template<>
string CHandlerPara< GETPAGE_FROM_WEBSITE1 >::parameters2("...")
其他模块将使用此模板获取相应的参数
并且可能为特殊行为指定 resultHandler 函数
最佳答案
非类型模板参数需要是编译时常量。将 int
转换为 const int
不会使其成为编译时常量。您要么需要直接使用 10
:
CAT<10> cat;
或者让i
成为const int
:
const int i = 10;
CAT<i> cat;
关于c++ - 使用模板时得到 "cannot appear in a constant-expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3984361/