Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 880
camino Avatar asked Oct 21 '10 04:10

camino


1 Answers

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;
like image 200
James McNellis Avatar answered Oct 07 '22 22:10

James McNellis