Jam*_*lis 17
要添加其他人所说的内容,请考虑以下constexpr函数模板:
template <typename T>
constexpr T add(T x, T y) { return x + y; }
Run Code Online (Sandbox Code Playgroud)
此constexpr功能模板是在某些情况下,一个常量表达式(例如,其中可用T是int),但不是在其他人(例如,其中T是用一个类类型operator+未声明过载constexpr).
constexpr并不意味着函数始终可用于常量表达式,这意味着该函数可用于常量表达式.
(有类似的例子涉及非模板函数.)
除了之前的答案之外:函数上的constexpr极大地限制了它的实现:它的主体必须对编译器可见(内联),并且必须只包含一个return语句.如果你能正确实现sqrt()或sin()并仍然满足最后一个条件,我会感到惊讶.
constexpr功能都没有pure,因为constexpr是一个提示,该函数可以在编译期间被计算编译器,如果它的参数是常数和操作在函数体mentionned,对于这些参数,本身constexpr.
后者使用模板代码,允许我们演示一个不纯的constexpr函数:
template <typename T>
constexpr T add(T lhs, T rhs) { return lhs + rhs; }
Run Code Online (Sandbox Code Playgroud)
用这种类型实例化
DebugInteger operator+(DebugInteger lhs, DebugInteger rhs) {
printf("operator+ %i %i", lhs._value, rhs._value);
return DebugInteger(lhs._value + rhs._value);
}
Run Code Online (Sandbox Code Playgroud)
这里,operator+不是constexpr,因此可以读/写全局状态.
我们可以说constexpr函数是pure在编译时进行评估的......但是就运行时而言,它只是被一个常量所取代.