Alecto
Alecto

Reputation: 10740

Is use of `auto` for a function argument against the C++ standard?

Does code like this:

auto add(auto a, auto b) { return a + b; }

violate the ISO c++14 standard? Will future versions of the standard allow code to be written like that?

Upvotes: 3

Views: 158

Answers (4)

HelpfulHelper
HelpfulHelper

Reputation: 294

For C++ 20 and above, this is valid and will behave as you might expect.

There is a workaround for compilers which dont support C++ 20, using function macros and templates:

#define add(a,b) add_real_function<decltype(a),decltype(b)>(a,b)

template <typename T1,typename T2>
auto add_real_function(T1 a, T2 b) { return a + b; }

Keep in mind that the real name of your function (add_real_function here) must differ from the name you want to give to your function(add here), which must be the name of the macro.

Unfortunately, this workaround comes with the drawback that you cannot create function pointers to these kind of functions.

Upvotes: -1

Barry
Barry

Reputation: 303186

[Does this] violate the ISO c++14 standard?

Yes, you can not declare functions taking parameters using auto in C++14 (or C++17 for that matter). This code is ill-formed.

Will future versions of the standard allow code to be written like that?

The current Concepts TS does allow for this, it's usually referred to as terse function template syntax. In Concepts, the meaning is equivalent to:

template <class T, class U>
auto add(T a, U b) { return a + b; }

That part of the Concepts proposal also allows concept names to be used, not just auto. It is an open question as to whether this will be part of a future C++ standard.


Update: The code will be valid in C++20, and have meaning equivalent to the function template I showed above (NB: a and b are deduced independently).

Upvotes: 7

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

template <typename T1, typename T2> int add(T1 a, T2 b);

Alternatively, you could use a lambda:

auto add = [](const auto& a, auto& b){ return a + b; };

is Proposal for Generic (Polymorphic) Lambda Expressions. However, generic lambdas are a C++14 feature.

Upvotes: 3

T33C
T33C

Reputation: 4429

At the moment this is invalid but maybe in a future version of the standard it will be the equivalent of:

template<typename T1, typename T2>
auto add(T1 a, T2 b) {return a + b;}

Upvotes: 1

Related Questions