得到了“不能出现在一个恒定的表达中”。使用模板时

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函数指定为特殊行为     
已邀请:
非类型模板参数需要是编译时常量。将
int
转换为
const int
并不会使它成为编译时常量。您需要直接使用
10
CAT<10> cat;
或者使
i
a
const int
const int i = 10;
CAT<i> cat;
    
了解哪些模板很重要:它们是针对特定模板类型或值的每种组合重新实例化的代码。
void f(const int j) { CAT<j> cat; } 
这要求
f
每次运行时创建不同类型的
CAT<>
,但必须在编译时解析模板。从概念上讲,编译器可能会应对,如果您只调用了
f()
,它可以在编译时解决,但如果您计划这样,那么您可以简单地写:
template <int N>
void f() { CAT<N> cat; }
这将生成多个创建自定义CAT&lt;>实例化的
f()
函数。 C ++标准甚至没有要求编译器暂时接受
void f(const int j)
版本 - 当有人在运行时确定使用它时,它只会是等待失败的可疑行李。在没有查看整个实现的情况下查看界面的人会期望
f()
可以使用这样的运行时值来调用 - 例如
f(atoi(argv[2]))
。或者,他们可能会把
for (int i = 0; i < 100000; ++i) f(i)
。如果
f()
在运行时取一个
int
,并且说它作为构造函数参数给出
CAT
(即作为运行时参数而不是模板参数)那么这很好,花花公子,但是如果编译器必须实例化100,000个版本的
f()
每个特殊的
CAT<>
s具有连续值
i/N
,可执行程序大小可能变得巨大(优化 - 如果启用 - 可以减轻这种情况)。     

要回复问题请先登录注册