c++ - static_assert 检查非模板类的模板构造函数中的值

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

因此,我正在寻找一种方法,如果用于声明对象的值等于另一个值(不希望使用 C 的 assert 宏),则会导致编译时错误.

是的,我知道为什么会出现这个问题......编译器在他/她提示expression did not evaluate to a constant时非常清楚。

我也不想让我的整个类(class)成为模板。是否有我缺少的神奇解决方法?

#include <iostream>

class test
{
private:
    template<class T, class T2>
    using both_int = std::enable_if_t<std::is_integral<T>::value && std::is_integral<T2>::value>;
private:
    int _a, _b;
public:

    template<class T, class T2 = T, class = both_int<T, T2>>
    constexpr test(const T &a, const T2 &b = 1)
        : _a(a), _b(b)
    {
        static_assert(b != 0, "Division by zero!");
    }
};

int main()
{
    test obj(1, 0); //ERROR

    test obj2(0, 1); //OK

    std::cin.get();
}

最佳答案

你可以这样做:

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

关于c++ - static_assert 检查非模板类的模板构造函数中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463455/

相关文章:

c++ - 矩阵遍历打印所有和最短路径 - 无限循环

c++ - Eclipse 中的 MakeFile 是什么?

c++ - 如何检索显示分辨率?

python-2.7 - jinja2 忽略最后一行?

c++ - 函数模板参数包后跟模板参数和特化

c++ - 使用相同的 Boost.Asio io_service 同步接受 tcp 连接并作为线程池

C++ 11在缺少时提供空的非成员函数

c++ - 替代 vector <bool>

c++ - 使用平截头体时 OpenGL 远剪裁

c++ - Variadic 模板方法和 std::function - 编译错误