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;
};