有没有一种方法可以在C++中将auto作为参数传递
Is there a way to pass auto as an argument in C++?
有没有办法将auto作为参数传递给另一个函数?
int function(auto data)
{
//DOES something
}
C++20允许auto
作为函数参数类型
此代码使用C++20:有效
int function(auto data) {
// do something, there is no constraint on data
}
作为一个缩写的函数模板。
这是非约束类型约束的特殊情况(即无约束自动参数)。使用概念,约束类型约束版本(即约束的自动参数)将是例如:
void function(const Sortable auto& data) {
// do something that requires data to be Sortable
// assuming there is a concept named Sortable
}
在我的朋友Yehezkel Bernat的帮助下,规范中的措辞:
9.2.8.5占位符类型说明符[dcl.spec.auto]
占位符类型说明符:
类型约束opt自动
类型约束optdecltype(自动)
占位符类型说明符指定占位符类型,稍后将由从初始化器。
表单的占位符类型说明符类型约束optauto可以在函数声明或lambda表达式的参数声明并且表示该函数是缩写函数模板(9.3.3.5)…
如果您希望这意味着您可以将任何类型传递给函数,请将其作为模板:
template <typename T> int function(T data);
有一个关于C++17的建议,允许您使用所使用的语法(就像C++14已经对通用Lambda所做的那样),但它还不是标准的。
C++2020现在支持自动功能参数。看看阿米尔的回答
模板是用普通函数实现这一点的方法:
template <typename T>
int function(T data)
{
//DOES something
}
或者,您可以使用lambda:
auto function = [] (auto data) { /*DOES something*/ };
我不知道它是什么时候改变的,但目前Question中的语法可以使用c++14:
https://coliru.stacked-crooked.com/a/93ab03e88f745b6c
只有一个警告:
g++-std=c++14-Wall-ppedantic-pthread-main.cpp&a.outmain.cpp:5:15:警告:参数声明中使用"auto"仅与-fconcepts一起使用无效功能(自动数据)
使用c++11时出现错误:
main.cpp:5:15:错误:参数声明中使用"auto"仅适用于-std=c++14或-std=gnu++14
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 在C++中将函数压缩为两种方式
- 如何在C++中将数组转换为矢量指针
- 在C++中将矢量转换为嵌套地图
- visual在c++中将十进制数转换为二进制数
- 在混合代码库中将C转换为C++时出现许多包含错误
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何在C++中将字符串传递给gets_s()
- 如何在C++中将整数转换为其数字数组
- 在C/C++中将变量名定义为__00000001有什么好处吗
- C++在数学计算中将double转换为int
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 如何在C++中将函数发送到另一个进程
- 如何在C++中将迭代器作为函数参数传递
- 如何在加密++中将两个源组合成新的源
- 如何在 c++ 中将数据与文件流分离
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 在Arduino中将PWM通道命名为LEDC是否有特定原因