got "cannot appear in a constant-expression" when using template

camino picture camino · Oct 21, 2010 · Viewed 37.5k times · Source
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  
  }  

even

   int i=10;  
   const int j=i;  
   CAT<j> cat; //this still can not work

but I have convert i to const int ,why compiler still report error ?
my platform is ubuntu,gcc version 4.4.3

Thanks,

==============

Thanks all for your input, but in some cases,I need a non-const variable ,

for example:

  //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("...")  

other module will using this template to get corresponding parameter
and maybe specilize the resultHandler function for a special behavior

Answer

James McNellis picture James McNellis · Oct 21, 2010

A non-type template argument needs to be a compile-time constant. Casting an int to a const int does not make it a compile-time constant. You either need to use 10 directly:

CAT<10> cat;

or make i a const int:

const int i = 10;
CAT<i> cat;