概念强加第二个参数的类型是int
Concepts impose the 2nd argument is of type int
正如标题所示,我希望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 =
是一个二进制概念(不管=
后面是什么(。这在某种程度上约束了两种不同的类型,T
和U
。无论你在这之后写什么,它实际上都不会解决你的用例。
你想说的是,一个类型是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
以下的任何整数类型。
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 指针问题:从不兼容的类型"int"分配给"int *"
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 错误:数组下标的类型"int[int]"无效
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- 运行时错误:有符号整数溢出:964632435 * 10 无法在类型 'int' 中表示
- 如何增加模板类型 int 参数?
- 尝试使用 Array 类的模板构造整数数组时,错误:为什么数组类型"int [5]"不可分配,
- 如何为底层类型 int 的枚举专门化类
- 数组下标编译的无效类型'int[int]'由于 -Wfatal 错误而终止
- 不能将 "const char*" 类型的值分配给类型 "int" 的实体
- 数组下标的无效类型INT [INT]
- 请求在"伺服控制器"中请求成员"附加",该成员属于非类类型"int"
- 数组类型 'int [8]'不可分配
- 未声明的标识符和类型"int"从 main 调用类时出现意外错误