Constexpr 函数 (C++11)
使用 constexpr 说明符声明的非构造函数是 constexpr 函数。 constexpr 函数是可以在常量表达式中调用的函数。
constexpr 函数必须满足以下条件:- 它不是虚拟的。
- 其返回类型为文字类型。
- 它的每个参数都必须是文字类型。
- 初始化返回值时,每个构造函数调用和隐式转换都在常量表达式中有效。
- 其函数体为
= delete或= default; 否则,其函数体必须仅包含以下语句:null语句static_assert声明- 未定义类或枚举的
typedef声明 using伪指令using声明- 一个
return语句
当使用 constexpr 说明符声明非构造函数的非静态成员函数时,该成员函数是常量,并且 constexpr 说明符对函数类型没有其他影响。 该函数所属的类必须是文字类型。
以下示例演示了
constexpr 函数的用法:const int array_size1 (int x) {
return x+1;
}
// Error, constant expression required in array declaration
int array[array_size1(10)];
constexpr int array_size2 (int x) {
return x+1;
}
// OK, constexpr functions can be evaluated at compile time
// and used in contexts that require constant expressions.
int array[array_size2(10)];
struct S {
S() { }
constexpr S(int) { }
constexpr virtual int f() { // Error, f must not be virtual.
return 55;
}
};
struct NL {
~NL() { } // The user-provided destructor (even if it is trivial)
// makes the type a non-literal type.
};
constexpr NL f1() { // Error, return type of f1 must be a literal type.
return NL();
}
constexpr int f2(NL) { // Error, the parameter type NL is not a literal type.
return 55;
}
constexpr S f3() {
return S();
}
enum { val = f3() }; // Error, initialization of the return value in f3()
// uses a non-constexpr constructor.
constexpr void f4(int x) { // Error, return type should not be void.
return;
}
constexpr int f5(int x) { // Error, function body contains more than
if (x<0) // return statement.
x = -x;
return x;
}
将函数模板声明为
constexpr 函数时,如果实例化导致函数不满足 constexpr 函数的需求,那么将忽略 constexpr 说明符。 例如:template <class C> constexpr NL f6(C c) { // OK, the constexpr specifier ignored
return NL();
}
void g() {
f6(55); // OK, not used in a constant expression
}对 constexpr 函数的调用在所有方面都会产生与对等效非constexpr 函数的调用相同的结果,但对 constexpr 函数的调用可能出现在常量表达式中。
constexpr 函数隐式内联。
无法使用 constexpr 说明符声明 main 函数。