C ++ 11 constexpr函数传递参数 [英] C++11 constexpr function pass parameter

查看:111
本文介绍了C ++ 11 constexpr函数传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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调用出错?

Why I have an error on make_const call?

更新

但这一项有效:

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 变量是相关的,但又有所不同。

A constexpr function and a constexpr variable are related, but different things.

一个 constexpr 变量是一个其值保证在编译时可用的变量。

A constexpr variable is a variable whose value is guaranteed to be available at compile time.

一个 constexpr 函数是一个函数,如果使用 constexpr 自变量求值,则并且在执行过程中表现为正确,将在编译时进行评估。

A constexpr function is a function that, if evaluated with constexpr arguments, and behaves "properly" during its execution, will be evaluated at compile time.

如果您传递了非 constexpr int constexpr 函数,它不会神奇地使其在编译时求值。但是,它将被允许通过其自身通过其输入参数的 constexpr ness(普通函数不能这样做)。

If you pass a non-constexpr int to a constexpr function, it will not magically make it evaluated at compile time. It will, however, be allowed to pass the constexprness of its input parameters through itself (normal functions cannot do this).

constexpr 是文档和对函数编写方式的限制以及对编译器的说明的混合体。

constexpr on functions is a mixture of documentation and restriction on how they are written and instructions to the compiler.

其背后的原因是允许在编译时和运行时都对同一函数进行求值。如果传递了运行时参数,则它是运行时函数。如果传递了 constexpr 参数,则可以在编译时对其进行评估(如果在某些上下文中使用,则将被评估)。

The reason behind this is to allow the same function to be evaluated both at compile time, and at run time. If passed runtime arguments, it is a runtime function. If passed constexpr arguments, it may be evaluated at compile time (and will be if used in certain contexts).

这篇关于C ++ 11 constexpr函数传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆