Is `auto` used for function argument versus C ++ standard?

Is there any code like this:

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

      

violate ISO C ++ 14 standard? Will future versions of the standard allow such code to be written?

+3


source to share


3 answers


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

Yes, you cannot declare functions that take parameters using auto

in C ++ 14 (or C ++ 17, for that matter). This code is poorly formed.

Will future versions of the standard code be written to do this?



The current TS concept does allow this, it is commonly referred to as the strong function pattern syntax. In concepts, the value is equivalent to:

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

      

This part of the Concepts also uses concept names, not only auto

. It is an open question as to whether this will be part of a future C ++ standard.

+6


source


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

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

      

Alternatively, you can use lambda:



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

      

Suggestion for generic (polymorphic) lambda expressions . However, generic lambdas are a C ++ 14 feature.

+3


source


This is not true at the moment, but perhaps in a future version of the standard it will be equivalent to:

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

      

+1


source







All Articles