static_assert用于检查非模板类的模板构造函数中的值

时间:2015-11-01 14:49:47

标签: c++ templates c++11 static-assert

所以,如果声明对象时使用的值等于另一个值(不想使用C' s {{},我正在寻找一种导致编译时错误的方法。 1}}宏)。

是的,我知道问题出现的原因......当他/她抱怨assert时,编译器非常清楚。

我也不想让我的全班成为模板。我错过了一个奇迹般的解决方法吗?

expression did not evaluate to a constant

1 个答案:

答案 0 :(得分:1)

你可以这样做:

struct test {
private:
  constexpr test(int a, int b) {}
public:
  template<int b>
  static test construct(int a) {
    static_assert(b != 0, "not zero failed");
    return test(a, b);
  }     
};

int main()
{
   test foo = test::construct<1>(1);
   test foo = test::construct<0>(1);//compile error
}

你需要静态构造函数,因为没有办法指定参数 模板构造函数,请参阅C++ template constructor