[英]C++11 constexpr function pass parameter
考虑以下代码:
static constexpr int make_const(const int i){
return i;
}
void t1(const int i)
{
constexpr int ii = make_const(i); // error occurs here (i is not a constant expression)
std::cout<<ii;
}
int main()
{
t1(12);
}
为什么我在 make_const 调用时出错?
更新
但这一个有效:
constexpr int t1(const int i)
{
return make_const(i);
}
但是,这不是:
template<int i>
constexpr bool do_something(){
return i;
}
constexpr int t1(const int i)
{
return do_something<make_const(i)>(); // error occurs here (i is not a constant expression)
}
constexpr
函数和constexpr
变量是相关的,但有所不同。
constexpr
变量是保证其值在编译时可用的变量。
constexpr
函数是一个函数,如果使用constexpr
参数对其求值, 并且在其执行过程中表现为“正确”,则该函数将在编译时求值。
如果将非constexpr
int
传递给constexpr
函数,则不会神奇地在编译时对其进行求值。 但是,将允许它通过自身传递其输入参数的constexpr
(正常功能不能这样做)。
关于函数的constexpr
是文档和对函数编写方式的限制以及对编译器的说明的混合体。
其背后的原因是允许在编译时和运行时都对同一函数进行求值。 如果传递了运行时参数,则它是运行时函数。 如果传递constexpr
参数,则可以在编译时对其进行评估(如果在某些上下文中使用,则将进行评估)。
const
和constexpr
之间的一个重要区别是,可以在编译时评估constexpr
。
通过编写constexpr int ii = make_const(i);
您告诉编译器该表达式将在编译时求值。 由于在运行时对i
进行了评估,因此编译器无法执行此操作,并给您一个错误。
由于t1()不是constexpr函数,因此参数i是运行时变量...您不能将其传递给constexpr函数。 Constexpr期望在编译时知道该参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.