C++,概念不适用于无符号整数作为结果类型?

C++, concepts not working with unsigned integers as a result type?

我正在玩弄 concepts 我试图定义一个 concept 接受任何 non-type parameter 并且函数 isUnsignedInt 检查参数是否是一个 unsigned int,使用 required 关键字后跟 concept.

问题是,我可以传递一个负整数并且没有错误消息,类型不是 unsigned int

我对概念的理解有误吗?

目前我正在使用 gcc 9.2 compiler 并且我的 CMake 包含 add_compile_options(-fconcepts),它启用 concepts.

代码:

template<auto a>
concept special = requires(){
    {a} -> unsigned int;
};

template<auto a> requires special<a>
constexpr auto isUnsignedInt(){
    return a;
}

int main(){
    std::cout << isUnsignedInt<-2>() << std::endl;
    return 0;
}

输出:

-2

这个:

{a} -> unsigned int;

不再是 C++20 将获得的概念版本中的内容。按理说,这应该是一个编译错误。但由于该更改最多仅在几个月前进行,因此它在您的编译器下编译也就不足为奇了。

由于它不再是有效的语法,真正的问题是它曾经是什么意思。这也解释了为什么他们将其删除。

该语法并不意味着 "this expression is the exact type unsigned int"。意思是 "this expression is implicitly convertible to the type unsigned int"。显然 int 可以隐式转换为 unsigned int,这就是为什么这个概念传递给负数的原因。

您认为它的意思是 "the same",尽管它并非如此,但这正是它被删除的原因。所以你必须明确地拼写出来:{a} -> std::same_as<unsigned int>,其中 std::same_as 是等同于特征 std::is_same_v 的概念。由于 GCC 可能还不包含标准库概念,因此您必须编写自己的等效项。