Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between a deduced template arg and auto arg?

Are these two functions different in any meaningful way? Is there any reason to generally prefer one over the other?

void foo(auto x, auto &... y) { /* ... */ }

template<typename T, typename... Tx>
void foo(T x, Tx &... y) { /* ... */ }

I would tend to use the first when I don't need the type T handy because it's shorter... but I'm wondering if there are any drawbacks.

like image 536
kylefinn Avatar asked Jan 25 '23 17:01

kylefinn


2 Answers

It is literally defined to be equivalent [dcl.fct]

An abbreviated function template is a function declaration that has one or more generic parameter type placeholders. An abbreviated function template is equivalent to a function template whose template-parameter-list includes one invented type template-parameter for each generic parameter type placeholder of the function declaration, in order of appearance.

Where generic type placeholders are the auto.

As with most equivalent syntax, it comes down to convention: pick one and stick with it.

like image 77
Passer By Avatar answered Jan 30 '23 02:01

Passer By


In the shown example, there is absolutely no difference between the 2 versions. Both are unconstrained function templates that take 1 argument of any type by value, and then 0 or more arguments of any types by reference.

Personally, like you, I prefer the first one, since it's less typing and easier to read.


You need to be careful when substituting one form for another, e.g. substituting:

template<typename T>
void foo(T x, T y) { /* ... */ }  // #1

with

void foo(auto x, auto y) { /* ... */ }  // #2 // not equivalent to #1

is incorrect, since there is no requirement on x and y to have the same type in #2, unlike in #1.

like image 37
cigien Avatar answered Jan 30 '23 02:01

cigien