+ 1

Templates vs auto

What is the advantage of using templates over the auto declaration? Template <class T> T somefunc(T a, T b) { return a+b; } vs auto someotherfunc(auto x, auto y) { return a+b; }

12th Nov 2016, 10:10 AM
Baptiste Corneglio
Baptiste Corneglio - avatar
2 Réponses
+ 3
in C++11 auto was redefined for using as a type inference, i.e. at compile time the type of the variable is deduced, by the way that implies no speed penalty. Another way, auto is applicable if and only if a variable is initialised. Furthermore, C++11 permitted automatically deducing the return type of a lambda function (consisted of only one return statement). in C++14 that has been expanded in two ways. First, lambda functions with automatically deduced return type works now with multiple return statements, as long as all returns using the same typ. Second, it now works with all functions ( under the same condition! ). example: #include <iostream> auto add(auto x,auto y) { if( x<0 ) return x+y; else return new int[5]; } int main(){ std::cout<<add(3,4.4); return 0; } compiler error: invalid conversion from int* to int -> the compiler assumed the return type to be int, thanks to the first return statement, but the second didnt match that type. The gcc 4.9.1 supports unconstrained generic functions, ie parameters of type auto, that didnt entered the final c++14 standard but there is a technical report, see www.stroustrup.com/C++11FAQ.html#what-concepts and link in the text. I didnt read it. Last thing I would like to mention is template classes cannt be implemented only using auto, ie. auto for private variables is illegal.
13th Nov 2016, 3:53 PM
siuilban
siuilban - avatar
+ 1
Thank you.
13th Nov 2016, 5:18 PM
Baptiste Corneglio
Baptiste Corneglio - avatar