如何使用 if constexpr
中的概念?
鉴于下面的例子,我们会给 if constexpr
什么?在 T
的情况下返回 1符合 integral
的要求还有0?
template<typename T>
concept integral = std::is_integral_v<T>;
struct X{};
template<typename T>
constexpr auto a () {
if constexpr (/* T is integral */) {
return 1;
}
else {
return 0;
}
}
int main () {
return a<X>();
}
最佳答案
Concepts在模板参数上命名为 boolean 谓词,在编译时进行评估。
在 constexpr if
中语句,条件的值必须是 bool
类型的上下文转换的常量表达式。
所以在这种情况下,用法很简单:
if constexpr ( integral<T> )
关于c++ - 如何在 if-constexpr 中使用概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54573420/