在我看来,拥有一个“总是返回5的函数”破坏或稀释了“调用函数”的意义。必须有一个原因,或者需要这个功能,否则它就不会出现在c++ 11中。为什么会在那里?
// preprocessor.
#define MEANING_OF_LIFE 42
// constants:
const int MeaningOfLife = 42;
// constexpr-function:
constexpr int MeaningOfLife () { return 42; }
在我看来,如果我写一个函数,返回一个字面值,然后我进行代码检查,有人会告诉我,我应该声明一个常量值,而不是返回5。
Stroustrup在“Going Native 2012”大会上的演讲如下:
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
它可以实现一些新的优化。Const传统上是类型系统的提示,不能用于优化(例如,Const成员函数可以合法地const_cast并修改对象,因此Const不能用于优化)。
Constexpr表示表达式真的是常量,前提是函数的输入是const。考虑:
class MyInterface {
public:
int GetNumber() const = 0;
};
如果这在其他模块中公开,编译器不能相信GetNumber()在每次调用时不会返回不同的值——甚至在两次调用之间没有非const调用的情况下也不会返回不同的值——因为const可能已经在实现中被丢弃了。(显然,任何这样做的程序员都应该被枪毙,但语言允许这样做,因此编译器必须遵守这些规则。)
添加constexpr:
class MyInterface {
public:
constexpr int GetNumber() const = 0;
};
编译器现在可以应用优化,缓存GetNumber()的返回值,并消除对GetNumber()的额外调用,因为constexpr是一个更强的保证,返回值不会改变。