在使用模板时得到"不能出现在常量表达式中"

cam*_*ino 9 c++ parameters templates non-type

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  
  }  
Run Code Online (Sandbox Code Playgroud)

甚至

   int i=10;  
   const int j=i;  
   CAT<j> cat; //this still can not work
Run Code Online (Sandbox Code Playgroud)

但我已将我转换为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("...")  
Run Code Online (Sandbox Code Playgroud)

其他模块将使用此模板获取相应的参数,
并可能为特殊行为指定resultHandler函数

Jam*_*lis 18

非类型模板参数需要是编译时常量.将an转换int为a const int不会使它成为编译时常量.您需要10直接使用:

CAT<10> cat;
Run Code Online (Sandbox Code Playgroud)

或者做i一个const int:

const int i = 10;
CAT<i> cat;
Run Code Online (Sandbox Code Playgroud)

  • @camino:那么它不能是模板.模板制作*类型*,类型是编译时构造.如果你有一个更具体的例子,我们可以提供帮助. (4认同)

Ton*_*roy 9

了解哪些模板很重要:它们是针对特定模板类型或值的每种组合重新实例化的代码.

void f(const int j) { CAT<j> cat; } 
Run Code Online (Sandbox Code Playgroud)

这要求fCAT<>每次运行时创建不同类型,但必须在编译时解析模板.从概念上讲,编译器可能会应对,如果您只调用f()它可以在编译时解决的值,但如果您计划这样做,那么您可以简单地写:

template <int N>
void f() { CAT<N> cat; }
Run Code Online (Sandbox Code Playgroud)

生成多个f()创建自定义CAT <>实例化的函数.

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<>小号具有连续值i/N 可执行程序的大小可能变得很大(优化 - 如果启用 - 可以减轻这种情况).