37

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)
{
    // ~
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Chunky Chunk
  • 16,553
  • 15
  • 84
  • 162

3 Answers3

15

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;
}
Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
  • 2
    it's important to outline that auto is fine and good 99% of the time, sometimes you have to stop for a second and think about what auto is really doing http://stackoverflow.com/questions/12773257/does-auto-type-assignments-of-a-pointer-in-c11-require pointers can be a corner case for auto. – user2485710 Aug 08 '13 at 20:53
  • 1
    @user2485710, added more info to my answer based on your comment. – Michael Goldshteyn Aug 08 '13 at 20:58
7

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
5

The only thing which makes it the auto keyword different from template that is you cannot make a generic class using the auto keyword.

class B { auto a; auto b; }

When you create an object of the above class it will give you an error.

B b; // Give you an error because compiler cannot decide type so it can not be assigned default value to properties

Whereas using template you can make a generic class like this:

template <class T> 

class B {
    T a;
};

void main() {
    B<int> b; //No Error
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
Danish Ahmed
  • 490
  • 5
  • 6