【问题标题】:C++ variable to const expressionC++ 变量到 const 表达式
【发布时间】:2011-06-02 04:12:02
【问题描述】:
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

这个问题与 Qt 无关,但在我的示例中有一行 Qt 代码。

setFrom() 和 setTo() 是基于用户选择通过 GUI 小部件调用的函数。我的问题的根源是'from'和'to'是变量。在我的计算成员函数中,我需要根据 'from' 和 'to' 的值选择一个类型(A、B 等)。我知道如何做我需要做的唯一方法是使用 switch 语句,但在我的情况下这非常乏味,我想避免。无论如何将错误行转换为常量表达式?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    不确定它是否有帮助,但您可以将您的值放在地图中并将其填充到其他地方,这样就没有繁琐的 switch 语句。

    【讨论】:

    • 不,抱歉,这没有帮助。填充地图仍然是很多工作;我有 22 个模板类,而且,仅针对所有 from/to 组合,我最终得到了 400 多个代码块。
    【解决方案2】:

    如果您不想使用switchif/else 块语句,那么您将无法完成此任务。因为at_c&lt;&gt;函数模板需要编译时需要知道的整数参数。并且您的变量 to_from_ 在编译时是未知的。

    我在以下主题中的回答与该主题有某种关联:

    C++ STL type_traits question


    或者可能(虽然我不确定)你可以编写一个从自身派生的类模板,每个基数都会减少整数 N 的值,然后类模板为特定值调度一个函数N.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      • 2023-02-26
      • 2014-02-20
      • 1970-01-01
      • 2018-01-17
      • 2011-09-03
      相关资源
      最近更新 更多