c++ - 如何在 if-constexpr 中使用概念?

标签 c++ c++-concepts c++20 if-constexpr

如何使用 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/

相关文章:

c++ - 从源代码本身获取输入 C++

C++ 概念精简版和类型别名声明

c++ - 我将如何在 C++20 中传递范围而不是迭代器对?

c++ - 如何在C++中构建八叉树

java - Visual Studio 2015 中 Visual C++ 开发中的 Jar 依赖项

c++ - C++ 中的概念检查变化?

c++ - 概念 std::equality_comparable_with 不适用于用户定义的相等运算符

c++ - std::tuple 可以在编译时/运行时根据其值进行排序吗

c++ - header 中的 "inline"是否需要 "void f(auto) {}"?

c++ - 使用 sin() 生成的声音中的金属声音