开发者

C++ variable to const expression

template <typename Real>
class A{ };

template <typename Real>
class B{ };
//... a few dozen more similar template classes

class Computer{

public slots:
 void setFrom(int from){ from_ = from; }
 void setTo(int to){ to_ = to; }

private:
 template <int F, int T> void compute(){

  using boost::fusion::vector;
  using boost::fusion::at_c;

  vector<A<float>, B<float>, ...> v;
  at_c<F>(v).operator()(at_c<T>(v));  //error; needs to be const-expression.
};

//...
computer.compute(1, 3);  // ok
computer.compute(var1, var2);  // var1, var2 cannot appear in a constant-expression

This question isn't about Qt, but there is a line of Qt code in my example.

The setFrom() and setTo() are functions that are called based on user selection via the GUI widget. The root of my problem is that 'from' and 'to' are variables. In my compute member function I need to pick a type (A, B, etc.) based on the values of 'from' and 'to'. The only way I know how to do what I need to do is to use 开发者_开发知识库switch statements, but that's extremely tedious in my case and I would like to avoid. Is there anyway to convert the error line to a constant-expression?


If you don't want to use switch or if/else block statements then there is no way you can accomplish this task. Because at_c<> function template takes integral parameter which needs to be known at compile time. And your variables to_ and from_ are not known at compile time.

And my answer in the following topic is somehow related to this topic:

C++ STL type_traits question


Or possibly (I'm not sure though) you can write a class template which derives from itself, each base decreasing the value of integral N and then class template dispatches a function for a particular value of N.


Not sure if it helps but you can put your values in a map and populate it elsewhere then there is no tedious switch statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜