【发布时间】:2015-02-19 22:04:15
【问题描述】:
拥有 '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 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)'
【问题讨论】:
-
你不能用模板做到这一点吗?更具体地说是使用非类型模板参数?
-
那么我的函数的用户应该提供不同的语法来调用它,具体取决于参数是否在编译时已知。
-
如果传入 constexpr 值,assert() 可能会被优化。
-
gcc 4.8.3 (cygwin x64) with -std=c++11 无法识别 constexpr 参数的使用。那是标准吗?我对 C++ 14 没有经验,但 constexpr-ness 是否可能是函数的一个属性,它可能会或可能不会在编译时计算,具体取决于参数的(隐式)constexpr-ness?
-
constexpr不是类型限定符。你想要它吗?我们已经有了const和volatile,它们一起提供了 4 种组合。我们真的需要更多吗?
标签: c++ language-lawyer c++14 compile-time