如果用户错误地实例化某个类的对象,如何强制编译器给出错误?
例如:
Polynomial a("x^2 + 2x + 1"); //this is a valid Polynomial object
Polynomial b("3xy + 2 - 5/z"); //this is not valid, force compiler error
static_assert
似乎不适用于函数参数,模板似乎不适用于字符串。如果无法在编译时执行此操作,那么在运行时执行此操作的好方法是什么?
最佳答案
我确实阅读并阅读了您的问题和评论,也许我很困惑您想要什么,但为什么使用 constexpr 构造函数的简单解决方案不适合您:
#include <iostream>
struct Polynomial {
const char* str;
constexpr Polynomial(char const* arg)
: str(arg) {
// if check fails when constructing constexpr Polynomial
// we get compile error for throwing, otherwise works
// if check fails when constructing runtime Polynomial
// then it does throw
if (arg[0] != 'b') throw 42;
}
};
int main() {
// should compile as first character is 'b'
constexpr Polynomial a("bar");
const char* foo = "foo";
try {
// should throw as first character is not 'b'
Polynomial b(foo);
} catch (...) {
std::cout << "Q.E.D." << std::endl;
}
}
这个 AFAIK 已经在 C++14 中工作了。
关于c++ - 强制编译时检查正确的对象实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70712181/