C++17 constexpr if 的一些用法示例

c++代码中使用 constexpr表达式能在编译期间进行求值,进而提升性能。而 constexpr if 带来的好处更近一步,不但有性能优势还能使得代码具有更好的可读性,以下是一些代码示例和说明:

S1:

template <typename T>
constexpr T getPositiveMinValue()
{
    if constexpr ((std::is_arithmetic<T>::value) && (std::is_floating_point<T>::value))
    {
        return sizeof(T) > 4 ? 1e-9 : 1e-7f;
    }
    else {
        return 0;
    }
}

S2:

std::string toAString(T t)
{
    if constexpr (std::is_same_v<T, std::string>)
        return t;
    else
        return std::to_string(t);
}

S3:

bool testLessFunc(float k)
{
    return k < 0.5f;
}
constexpr int testLess(float k) {
    return k < 0.5f ? 0 : 1;
}
int main(int argc, char *argv[])
{

    float argc_float = static_cast<float>(argc);
    //if (constexpr(1 == testLess(0.5f)))           // eror: 错误的语法形式
    //if constexpr (argc_float == testLess(0.5f))   // error: 表达式必须含有常量值
    //if constexpr(1 == testLess(0.5f))             // OK
    //if constexpr (testLessFunc(0.5f))             // error: 表达式必须含有常量值
    if constexpr( testLess(0.5f) )                  // OK
    //if constexpr (testLess(argc_float))           // error: 表达式必须含有常量值
    //if constexpr (true)                           // OK
    {
        std::cout << "constexpr if syntax apply success." << std::endl;
    }
    else
    {
        std::cout << "constexpr if syntax apply failure." << std::endl;
    }

}

S4:

class V3
{
public:
    ~V3() = default;

    constexpr V3(T x, T y, T z) noexcept :
        x(x), y(y), z(z)
    {}
    V3()                         = default;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值