我有一个类 C
并且想要执行以下操作:
class C {
public:
C(const size_t aa, const size_t bb) { // aa and bb are compile time constants
// when aa + bb > 10 raise a compile time error
}
private:
size_t a;
size_t b;
}
构造函数 C::C
应该进行类型检查并拒绝任何在编译时未知的 aa
和 bb
值正整数。如果检查通过,编译器应该检查它们的总和。如果总和大于 10,编译器应该拒绝构造函数调用。
仅使用 ISO C++11 而不依赖于特定的编译器是否可行(以及如何实现)?
最佳答案
在编译时,您所要求的只能通过模板实现,例如:
template<size_t aa, size_t bb>
class C {
public:
C() {
static_assert(aa > 0, "aa must be > 0");
static_assert(bb > 0, "bb must be > 0");
static_assert((aa + bb) <= 10, "aa + bb must be <= 10");
}
};
C<1, 2> c1; // OK
C<5, 6> c2; // compile error
否则,在运行时,您所能做的就是在输入错误时抛出异常,例如:
#include <stdexcept>
class C {
public:
C(const size_t aa, const size_t bb) : a(aa), b(bb) {
if (aa == 0)
throw std::runtime_error("aa must be > 0");
if (bb == 0)
throw std::runtime_error("bb must be > 0");
if ((aa + bb) > 10) {
throw std::runtime_error("aa + bb must be <= 10");
}
}
private:
size_t a;
size_t b;
};
C c1(1, 2); // OK
C c2(5, 6); // runtime error
关于c++ - 根据参数值产生编译时错误的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61417147/