Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Templates vs. Auto Keyword

Can the auto keyword in C++11 replace function templates and specializations? If yes, what are the advantages of using template functions and specializations over simply typing a function parameter as auto?

template <typename T> void myFunction(T &arg) {     // ~ } 

vs.

void myFunction(auto &arg) {     // ~ } 
like image 510
Chunky Chunk Avatar asked Aug 08 '13 20:08

Chunky Chunk


People also ask

What are the differences between function template and template function?

Function Template is the correct terminology (a template to instantiate functions from). Template Function is a colloquial synonym. So, there's no difference whatsoever.

What is a function template?

Function templates are similar to class templates but define a family of functions. With function templates, you can specify a set of functions that are based on the same code but act on different types or classes.

What is the advantage of template functions?

Because their parameters are known at compile time, template classes are more typesafe, and could be preferred over run-time resolved code structures (such as abstract classes). There are some modern techniques that can dramatically reduce code bloat when using templates.

What is auto template?

An auto keyword in a template parameter can be used to indicate a non-type parameter the type of which is deduced at the point of instantiation. It helps to think of this as a more convenient way of writing: template <typename Type, Type value>


2 Answers

In a nutshell, auto cannot be used in an effort to omit the actual types of function arguments, so stick with function templates and/or overloads. auto is legally used to automatically deduce the types of variables:

auto i=5; 

Be very careful to understand the difference between the following, however:

auto x=... auto &x=... const auto &x=... auto *px=...; // vs auto px=... (They are equivalent assuming what is being                //                 assigned can be deduced to an actual pointer.) // etc... 

It is also used for suffix return types:

template <typename T, typename U> auto sum(const T &t, const U &u) -> decltype(t+u) {   return t+u; } 
like image 141
Michael Goldshteyn Avatar answered Oct 14 '22 16:10

Michael Goldshteyn


Can the auto keyword in C++11 replace function templates and specializations?

No. There are proposals to use the keyword for this purpose, but it's not in C++11, and I think C++14 will only allow it for polymorphic lambdas, not function templates.

If yes, What are the advantages of using template functions and specializations over simply typing a function parameter as auto.

You might still want a named template parameter if you want to refer to the type; that would be more convenient than std::remove_reference<decltype(arg)>::type or whatever.

like image 37
Mike Seymour Avatar answered Oct 14 '22 17:10

Mike Seymour