有没有一种方法可以在C++中将auto作为参数传递

Is there a way to pass auto as an argument in C++?

本文关键字:中将 C++ auto 参数传递 方法 一种 有没有      更新时间:2023-10-16

有没有办法将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(自动)

  1. 占位符类型说明符指定占位符类型,稍后将由从初始化器。

  2. 表单的占位符类型说明符类型约束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