How can I have a temporary variable in a constexpr function?

浪尽此生 提交于 2019-12-05 10:02:41

As you've discovered, you can't declare variables, even constexpr ones, inside the body of a constexpr function.

It's still possible to factor out a common expression, by passing it in as an argument to a second constexpr function. For the example you've given here:

constexpr float pow3(float c) {
    return c*c*c;
}

constexpr float f(float a, float b) {
    return pow3(a+b);
}

This is not permitted in C++11, but is now permitted in C++14.

See https://en.wikipedia.org/wiki/C%2B%2B14#Relaxed_constexpr_restrictions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!