概念强加第二个参数的类型是int

Concepts impose the 2nd argument is of type int

本文关键字:类型 int 参数 第二个      更新时间:2024-09-29

正如标题所示,我希望foo只接受int类型作为它的第二个参数。

#include <iostream>
#include <concepts>
#include <type_traits>
template <typename U, typename T>  concept IS_INT =
requires (U u, T t) {
{ t + 0 } -> std::same_as<int>;
};

IS_INT {U, T}
void foo (U u, T t)
{
std::cout << "IS INT!" << std::endl;
return;
}

int main()
{
foo(1, 1);
return 0;
}

它正在工作,但g++(版本10.2.0(正在生成此警告

test.cpp:11:8: warning: template-introductions are not part of C++20 concepts [-fconcepts-ts]
11 | IS_INT {U, T}
| ~~~~~~~^~~~~~

编写IS_INT {U, T}的替代方法?摆脱这个警告?


最后,如何在不添加0的情况下重写此约束(t为int(?

{ t + 0 } -> std::same_as<int>;

编辑

template <typename U, typename T>  concept IS_INT =
requires (U u, T t) {
std::same_as<T, int>;
};

没有给出的编译错误

foo(1, "TTT");

即使在当前的核心概念版本中,也可以保持二进制形式

template <typename U, typename T>  concept IS_INT =
requires (U u, T t) {
{ t + 0 } -> std::same_as<int>;
};

template<class T, IS_INT<T> U>
void foo (U u, T t)
{
std::cout << "IS INT!" << std::endl;
return;
}

(注意逆参数顺序:通常,如果一个概念接受多个参数,那么只有第一个参数是特殊的,U在定义中是第一个(。正如g++警告的那样,全TS糖目前还不是标准的。

最后,如何在不添加0的情况下重写此约束(t为int(?

template<class T, class U> concept is_int = std::same_as<T, int>;

正如标题所示,我希望foo只接受int类型作为它的第二个参数。

这是在请求一个一元概念-您希望将第二个参数本身约束为int。这是在检查单个类型的需求。

此:

template <typename U, typename T>  concept IS_INT =

是一个二进制概念(不管=后面是什么(。这在某种程度上约束了两种不同的类型,TU。无论你在这之后写什么,它实际上都不会解决你的用例。

你想说的是,一个类型是int。即:

template <typename T> concept is_int = std::is_same_v<T, int>;

你可以使用,因此:

template <typename U, is_int T>
void foo (U u, T t);

这对第一个参数没有约束,第二个参数的类型必须为int


现在,标准库实际上为这个问题提供了一个概念。它被称为same_as:

template <typename U, std::same_as<int> T>
void foo (U u, T t);

此外,值得注意的是要求:

{ t + 0 } -> std::same_as<int>;

实际上并不要求t具有类型int。由于整数提升,这也适用于int以下的任何整数类型。