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

Viewed 99

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.

3 Answers

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.

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.

Are these two functions different in any meaningful way?

Yes. The latter is responsible for more repetitive stress injury than the former, not least because banging your head on the keyboard is both repetitive and injury-inducing.

A lot of software engineering is about dealing with the limitations and needs of humans, not machines. Even seemingly machine-centric aspects such as performance only matter to the extent that some humans might care (be those some users who'd like a smoother experience, or developers whose bodies just won't take another round of hallway swordfighting, or shareholders who get night sweats when someone the size of Facebook sees a 1% performance drop across their infrastructure - at which scale the losses are measured in gold ball bearings freely falling out the spout of a large funnel).

The almost Ada-like verbosity in which the entirety of the template-surrounding syntax is mired in is not ergonomic in the least. Ergonomy plays a big role in making us happy at the end of the day, so yes, it is surely meaningful in the full sense of the word. It is not a difference that's meaningful much to the compiler, but by that standard we'd be writing machine code directly in base 2^6 using Braille punches: what's arbitrary to the machine is not necessarily all that arbitrary to us!

Related