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

对着背影说爱祢 提交于 2019-11-26 21:06:27

问题


Is there a way to pass auto as an argument to another function?

int function(auto data)
{
    //DOES something
}

回答1:


If you want that to mean that you can pass any type to the function, make it a template:

template <typename T> int function(T data);

There's a proposal for C++17 to allow the syntax you used (as C++14 already does for generic lambdas), but it's not standard yet.




回答2:


Templates are the way you do this with normal functions:

template <typename T>
int function(T data)
{
    //DOES something
}

Alternatively, you could use a lambda:

auto function = [] (auto data) { /*DOES something*/ };



回答3:


I dont know when it changed, but currently syntax from Question is possible with c++14:

https://coliru.stacked-crooked.com/a/93ab03e88f745b6c

There is only warning about it:

g++ -std=c++14 -Wall -pedantic -pthread main.cpp && ./a.out main.cpp:5:15: warning: use of 'auto' in parameter declaration only available with -fconcepts void function(auto data)

With c++11 there is an error:

main.cpp:5:15: error: use of 'auto' in parameter declaration only available with -std=c++14 or -std=gnu++14



来源:https://stackoverflow.com/questions/29944985/is-there-a-way-to-pass-auto-as-an-argument-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!