// 1 constexpr 对象和const对象一样,是编译期可知的
// constexpr 对象都是const的,但不是所有const都是constexpr
// const 不提供constexpr所保证之事,因为const对象不需要在编译期初始化它的值
int sz; // non-constexpr
constexpr auto arraysize1 = sz; // error,sz的值在编译期不可知
std::array<int, sz> data1; // error; same as front
constexpr auto arraysize2 = 10; // 没问题,10是编译期可知常量
std::array<int, arraysize2> data2; // 没问题,arraysize2是constexpr
int sz;
const auto arraysize = sz; // 没问题,arraysize是sz的const复制
std::array<int, arraysize> data; // 错误,arraysize是编译期不可知的
// 2 当一个constexpr函数被一个或者多个编译期不可知调用时,就像普通函数一个运行时计算结果。这意味着你不需要两个函数,一个用于编译期计算,一个用于运行时计算
// 实现一个pow函数用于 std::array
// constexpr 不表明pow返回一个const值,它只说明如果base和exp是编译期常量,pow的值可以被当成编译期常量使用。如果base 或exp不是编译期常量,pow的结果将会在运行时计算
constexpr int pow(int base, int exp) noexcept {
...
}
constexpr auto numConds = 5;
std::array<int, pow(3, numConds)> result;
// 3 constepxr class 基本上意味着那些有了值的类型能在编译期决定,因此能被array size等使用
// 另外,constexpr会增加编译耗时,但会减少运行时耗时
// 缺点,代码重构时可能会发现很多和constexpr相关的代码不能使用
class Point {
public:
constexpr Point (double xVal = 0, double yVal = 0) noexcept: x(xVal), y(yVal) {}
constexpr double xValue() const noexcept { return x; }
constexpr double yValue() const noexcept { return y; }
void setX(double newX) noexcept { x = newX; }
void setY(double newY) noexcept { y = newY; }
private:
double x,y;
};
// uses
constexpr Point midPoint(const Point& p1, const Point& p2) noexcept {
return {(p1.xValue() + p2.xValue()) / 2, (p1.yValue() + p2.yValue()) / 2};
}
constexpr auto mid = midPoint(p1, p2);
item15 尽量使用constexpr
最新推荐文章于 2025-02-19 23:09:16 发布