4.3.1 const和constexpr
const语义上其实是只读(readonly),const并未区分出编译期常量和运行期常量; constexpr限定在了编译期常量, 此外constexpr修饰函数写在函数前面,const修饰函数写在后面,并且函数为只读函数
示例代码1:
#include <array>
using namespace std;
constexpr int foo(int i)
{
return i + 5;
}
int main()
{
int i = 10;
std::array<int, foo(5)> arr; // OK
foo(i); // Call is Ok
// But...
std::array<int, foo(i)> arr1; // Error
}
如果函数体适用于constexpr函数的条件,可以尽量加上constexpr。而检测constexpr函数是否产生编译时期值的方法很简单,就是利用std::array需要编译期常值才能编译通过的小技巧。
示例代码2:
class MyClass {
public:
int getValue() const {
return value;
}
private:
int value;
};