为什么我不能增加简单 constexpr 函数的参数?
Why I can't increment the parameter of the simple constexpr function?
Visual Studio 2015 更新 3.
我读了编程。使用 C++ 的原理和实践(第二版),作者 Bjarne Stroustrup。我学习了 constexpr
函数...
有效:
constexpr int get_value(int n) {
return n + 1;
}
但我无法编译这个(而不是第一个变体):
constexpr int get_value(int n) {
return ++n;
}
我收到错误:
constexpr function return is non-constant
n
是 get_value
函数的 local 变量。 IE。 n
变量改变不影响外部代码。
为什么 get_value
函数的第二个变体是错误的?
第二个在 C++14 下是合法的,但它无法编译,因为 Visual Studio 2015 仅部分支持 constexpr
函数。它仅支持单个 return constexpr
函数和其他限制(如您的限制),这在 C++11 中有效。
参见 this 文章(在 constexpr
段中)。 Visual Studio“15”将改进 constexpr
功能。您需要稍等一下:)
第二个在 C++11 中是不允许的 constexpr
。该标准甚至有一个非常相似的示例 (N3337 [dcl.constexpr]/3):
constexpr int prev(int x)
{ return --x; } // error: use of decrement
N3337 [expr.const]/2 明确禁止在常量表达式中使用 "increment or decrement operations"。
C++14 扩展 constexpr
放宽了这些要求,但 MSVC 没有实现。
Visual Studio 2015 更新 3.
我读了编程。使用 C++ 的原理和实践(第二版),作者 Bjarne Stroustrup。我学习了 constexpr
函数...
有效:
constexpr int get_value(int n) {
return n + 1;
}
但我无法编译这个(而不是第一个变体):
constexpr int get_value(int n) {
return ++n;
}
我收到错误:
constexpr function return is non-constant
n
是 get_value
函数的 local 变量。 IE。 n
变量改变不影响外部代码。
为什么 get_value
函数的第二个变体是错误的?
第二个在 C++14 下是合法的,但它无法编译,因为 Visual Studio 2015 仅部分支持 constexpr
函数。它仅支持单个 return constexpr
函数和其他限制(如您的限制),这在 C++11 中有效。
参见 this 文章(在 constexpr
段中)。 Visual Studio“15”将改进 constexpr
功能。您需要稍等一下:)
第二个在 C++11 中是不允许的 constexpr
。该标准甚至有一个非常相似的示例 (N3337 [dcl.constexpr]/3):
constexpr int prev(int x)
{ return --x; } // error: use of decrement
N3337 [expr.const]/2 明确禁止在常量表达式中使用 "increment or decrement operations"。
C++14 扩展 constexpr
放宽了这些要求,但 MSVC 没有实现。