星座函数 (C++11)
注: IBM 支持 C++11的所选功能,在批准之前称为 C++0x 。 IBM 将继续开发和实施此标准的功能部件。 语言级别的实现基于 IBM对标准的解释。 在完成 IBM对所有 C++11 功能部件的实现 (包括对新的 C++11 标准库的支持) 之前,实现可能会随着发行版而更改。 IBM 不会尝试在源代码,二进制或列表以及其他编译器接口中维护与 IBM的先前发行版实现新的 C++11 功能部件的兼容性。
声明的非构造函数constexpr说明符是constexpr功能。 Aconstexprfunction 是可以在常量表达式中调用的函数。
Aconstexpr函数必须满足以下条件:
- 它不是虚拟的。
- 其返回类型为文字类型。
- 它的每个参数都必须是文字类型。
- 初始化返回值时,每个构造函数调用和隐式转换都在常量表达式中有效。
- 其功能体为= 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 return statement.
if (x<0)
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函数可以出现在常量表达式中。
Aconstexpr函数隐式内联。
该main不能使用constexpr说明符。