为什么不允许';stexpr';参数?
为了区分编译器已知值,从而能够在编译时检测错误,使用‘constexpr’参数会很有用。示例:
int do_something(constexpr int x)
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
int do_something(int x)
{
if(x > 0) { cout << "x must be > 0" << endl; exit(-1); }
return x + 5;
}
int var;
do_something(9); //instance 'do_something(constexpr int x)' and check arg validity at compile time
do_something(0); //produces compiler error
do_something(var); //instance 'do_something(int x)'
目前这是无效代码。有人能给我解释一下为什么这不能实施吗?
编辑:
使用模板时,用户必须始终将文字作为模板参数传递,而不是作为函数参数传递,这非常不舒服:
template<int x>
int do_something()
{
static_assert(x > 0, "x must be > 0");
return x + 5;
}
int do_something(int x)
{
if(x > 0) { cout << "x must be > 0" << endl; exit(-1); }
return x + 5;
}
int var;
do_something(9); //instance 'do_something(int x)' and doesn't check validity at compile time
do_something(0); //same as above, if check was performed - compiler error should occur
do_something<9>(); //instance template 'do_something<int>()'
do_something<0>(); //produces compiler error
do_something(var); //instance 'do_something(int x)'
解决方案
如果我了解您尝试正确执行的操作,则您请求的功能已经可用。这不是最雅致的,但我认为这已经足够好了。
您希望在编译时和运行时使用相同的语法调用函数,如果可能,让它在编译时求值,否则它应该在运行时求值。无论何时调用函数,您都需要对该函数计算断言。我相信这会满足您的要求:
constexpr int do_something(int x)
{
if(x <= 0)
{
std::cout << "x must be > 0" << std::endl; exit(-1);
}
return x + 5;
}
constexpr int compiletime_good = do_something(5);
constexpr int compiletime_bad = do_something(0); // Fails at compile-time
int runtime_good = do_something(5);
int runtime_bad = do_something(0); // Fails at runtime
constexpr int val_good = 5;
constexpr int val_bad = 0;
do_something(val_good);
do_something(val_bad); // Fails at run-time
int valrun_good = 5;
int valrun_bad = 0;
do_something(valrun_good);
do_something(valrun_bad); // Fails at run-time
这里的诀窍是在编译时以不需要静电_ASSERT的方式失败,在运行时也会失败。
相关文章