talk
在这里,冻结库的作者解释了他如何在constexpr函数中使用assert及其工作原理(因为在运行时它可以正常工作,而在编译时它会触发函数的非constexpr执行,从而发生编译器错误)。
另外,不能对函数参数使用静态断言,因为它们不是constexpr,而且我不想将函数参数移到<&燃气轮机;使它们成为constexpr。这就是我想要避免的转变的例子:
constexpr unsigned int safe_right_shift(const unsigned int val, const unsigned shift){
assert(shift<sizeof(unsigned int)*CHAR_BIT); //ugly error
return val >>shift;
}
template<unsigned int shift>
constexpr unsigned int safe_right_shift_t(const unsigned int val){
static_assert(shift<sizeof(unsigned int)*CHAR_BIT);
return val >>shift;
}
在C++17中,有没有更好的方法来实现假设的constexpr\u断言?
我将constexpr\u assert定义为只在constexpr求值(又称编译时)期间检查值的断言。
错误:
注意:非constexpr函数“\u assert\u fail”不能在常量表达式中使用
full code