为什么不允许使用"constexpr"参数? [英] Why 'constexpr' parameters are not allowed?
问题描述
使用"constexpr"参数来区分编译器已知的值,从而能够在编译时检测错误,将很有用.例子:
It would be useful to have 'constexpr' parameters in order to distinguish compiler-known values and so to be able detecting errors at compile-time. Examples:
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)'
这是一个无效的代码.有人可以向我解释为什么这不能实现吗?
Which is an invalid code for now. Can somebody explains me why this can't be implemented?
使用模板的用户应确保文字总是作为模板参数而不是作为函数参数传递,这是非常不舒服的:
Using templates users should assure that literals are always passed as template arguments and not as function ones which is very uncomfortable:
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 checks 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)'
推荐答案
如果我了解您要正确执行的操作,则您所请求的功能已经可用.这不是最优雅的,但我认为这已经足够了.
If I'm understanding what you're trying to do correctly, the functionality you are requesting is already available. It's not the most elegant, but I think this is good enough.
您希望使用相同的语法在编译时和运行时调用一个函数,并在可能的情况下让它在编译时求值,否则应在运行时求值.无论何时调用该函数,都需要对函数求值.
我相信这会满足您的要求:
I believe that this will do what you want:
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
这里的窍门是在编译时以不需要static_assert的方式失败,并且也将在运行时失败.
这篇关于为什么不允许使用"constexpr"参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!