c++ - 使用模板时得到 "cannot appear in a constant-expression"

标签 c++ templates parameters 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  
  }  

甚至

   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/

相关文章:

c++ - 包含下采样的去马赛克算法

c++ - MFC中如何保存数据?

c++ - vector 中连续数字的计数

安卓设计模板

java - 如何在java中将自定义请求位置放入HttpURLConnection中

ruby-on-rails - 在 link_to 中传递参数

c++ - 如何为不同文件夹中的多个 .cpp 文件和 header 编写 Cmake?

c++ - boost 中的模板无效元函数

c++ - 如何使用需要非常量引用的函数编写 decltype 表达式?

java - 在 java 中找不到在参数中传递的变量