因此,我正在寻找一种方法,如果用于声明对象的值等于另一个值(不希望使用 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/