Boost logo

Boost Users :

From: François Duranleau (duranlef_at_[hidden])
Date: 2006-03-17 00:37:48


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<s,i>::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.

-- 
François Duranleau
LIGUM, Université de Montréal
"A person's truth is so simple that most ignore it to concentrate on what
  they think are deeper truths."
                                           - from _Neon Genesis Evangelion_

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net