为什么我不能递增简单 constexpr 函数的参数?

Why I can't increment the parameter of the simple constexpr function?

本文关键字:函数 参数 constexpr 简单 不能 为什么      更新时间:2023-10-16

Visual Studio 2015更新3。

我读了编程。Bjarne Stroustrup的《使用C++的原理与实践》(第二版)。我学习了constexpr函数。。。

它起作用:

constexpr int get_value(int n) {
    return n + 1;
}

但我无法编译这个(而不是第一个变体):

constexpr int get_value(int n) {
    return ++n;
}

我得到错误:

constexpr函数返回的是非常量

nget_value函数的局部变量。即n变量的变化对外部代码没有影响。

为什么get_value函数的第二个变体是错误的?

第二个在C++11 constexpr中是不允许的。该标准甚至有一个非常相似的例子(N3337[dcl.constexpr]/3):

constexpr int prev(int x)
{ return --x; } // error: use of decrement

N3337[expr.const]/2明确禁止常量表达式中的"递增或递减操作"。

C++14扩展的constexpr放宽了这些要求,但MSVC没有实现这些要求。

第二个在C++14下是合法的,但它不能编译,因为Visual Studio 2015只部分支持constexpr函数。它只支持单返回constexpr函数和其他限制(如您的),这些限制在C++11中有效。

请参阅本文(constexpr段)。Visual Studio"15"将对constexpr功能进行改进。您需要等待一段时间:)