首页 > 解决方案 > 在布尔上下文中使用具有非类型模板参数包的概念

问题描述

在 C++20 中,我AllIntegral使用非类型模板参数包定义了一个概念auto... T_values。虽然 GCC 10.1.0 在某些情况下接受它的使用,但它拒绝在其他情况下编译它的使用,尤其是在 if声明中。相关的错误消息说“AllIntegral”不限制类型

我的代码如下所示:

#include <concepts>
#include <ios>
#include <iostream>

template<auto... T_values>
concept AllIntegral = (std::integral<decltype(T_values)> && ...);

int main()
{
    std::cout << std::boolalpha << AllIntegral<1, 2> << '\n';  // compiles and prints "true"
    if (AllIntegral<1, 2>) std::cout << "true" << '\n';        // does not compile

    std::cout.flush();
}

这是编译器输出:

main.cpp: In function ‘int main()’:
main.cpp:11:9: error: ‘AllIntegral’ does not constrain a type
   11 |     if (AllIntegral<1, 2>) std::cout << "true" << '\n';
      |         ^~~~~~~~~~~~~~~~~
main.cpp:6:9: note: concept defined here
    6 | concept AllIntegral = (std::integral<decltype(T_values)> && ...);

这个错误的原因是什么?为什么我的概念不能在布尔上下文中使用?

标签: c++c++20c++-conceptsnon-type-template-parameter

解决方案


推荐阅读