Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

int function(auto data) {     //DOES something } 
like image 952
user3639557 Avatar asked Apr 29 '15 13:04

user3639557


People also ask

Can you pass a function as an argument in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

Can you pass a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.

Can we pass Auto as a parameter to function C++?

C++20 allows auto as function parameter typeAs an abbreviated function template. A placeholder-type-specifier designates a placeholder type that will be replaced later by deduction from an initializer.


2 Answers

C++20 allows auto as function parameter type

This code is valid using C++20:

int function(auto data) {    // do something, there is no constraint on data } 

As an abbreviated function template.

This is a special case of a non constraining type-constraint (i.e. unconstrained auto parameter). Using concepts, the constraining type-constraint version (i.e. constrained auto parameter) would be for example:

void function(const Sortable auto& data) {     // do something that requires data to be Sortable     // assuming there is a concept named Sortable } 

The wording in the spec, with the help of my friend Yehezkel Bernat:

9.2.8.5 Placeholder type specifiers [dcl.spec.auto]

placeholder-type-specifier:

type-constraintopt auto

type-constraintopt decltype ( auto )

  1. A placeholder-type-specifier designates a placeholder type that will be replaced later by deduction from an initializer.

  2. A placeholder-type-specifier of the form type-constraintopt auto can be used in the decl-specifier-seq of a parameter-declaration of a function declaration or lambda-expression and signifies that the function is an abbreviated function template (9.3.3.5) ...

like image 29
Amir Kirsh Avatar answered Sep 27 '22 23:09

Amir Kirsh


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.

Edit: C++ 2020 now supports auto function parameters. See Amir's answer below

like image 115
Mike Seymour Avatar answered Sep 27 '22 23:09

Mike Seymour