
François Duranleau
On Thu, 16 Mar 2006, John Christopher wrote:
void operator()(const int& i) { switch(i) { case 0: vec.push_back(new T0); break; case 1: vec.push_back(new T1); break; } // I'd like to simplify the above swtich statement by writing something like: vec.push_back(new boost::mpl::at
::type); // but it does not compile and MinGW returns: // error: i cannot appear in a constant expression // error: template argument 2 is invalid. }Of course it doesn't compile, because non-type template arguments must be constants known at compile time. However here, the parameter i isn't, and thus cannot be used as a template argument. It would seem like you are stuck with a switch, unless you create something like an array of generating function, e.g.:
template < typename T > Tbase* genT() { return new T ; }
typedef Tbase* (* genT_type)() ; genT_type generators[] = { & genT< T0 > , & genT< T1 > } ;
//... void operator () ( const int i ) { vec.push_back( generators[ i ]() ) ; }
It won't be as efficient as the switch though because of the function call through a function pointer.
Chapter 11 of "C++ Template Metaprogramming" shows how to generate the equivalent of a switch statement using the MPL. -- Dave Abrahams Boost Consulting www.boost-consulting.com