得到了“不能出现在一个恒定的表达中”。使用模板时
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
但我已将我转换为const int,为什么编译器仍报告错误?
我的平台是ubuntu,gcc版本4.4.3
谢谢,
==============
谢谢你的输入,但在某些情况下,我需要一个非const变量,
例如:
//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函数指定为特殊行为
没有找到相关结果
已邀请:
2 个回复
死狸蔽垂藐
转换为
并不会使它成为编译时常量。您需要直接使用
:
或者使
a
:
殿虫
这要求
每次运行时创建不同类型的
,但必须在编译时解析模板。从概念上讲,编译器可能会应对,如果您只调用了
,它可以在编译时解决,但如果您计划这样,那么您可以简单地写:
这将生成多个创建自定义CAT&lt;>实例化的
函数。 C ++标准甚至没有要求编译器暂时接受
版本 - 当有人在运行时确定使用它时,它只会是等待失败的可疑行李。在没有查看整个实现的情况下查看界面的人会期望
可以使用这样的运行时值来调用 - 例如
。或者,他们可能会把
。如果
在运行时取一个
,并且说它作为构造函数参数给出
(即作为运行时参数而不是模板参数)那么这很好,花花公子,但是如果编译器必须实例化100,000个版本的
每个特殊的
s具有连续值
,可执行程序大小可能变得巨大(优化 - 如果启用 - 可以减轻这种情况)。