Reputation: 594
I am writing an identity function for some of my classes that keeps a count of its calls (long story -> short: metrics).
At the moment, I'm trying to figure the performance differences/benefits of using a template vs auto
.
Here is a short example taken from my code of what I'm doing:
namespace Metrics {
unsigned long identifications = 0;
//auto version
auto identity(auto i) {
//... other stuffs
identifications++;
return i;
};
//template version
template<class I> I identity(I i) {
//... other stuffs
identifications++;
return i;
};
};
There's a bit more going on, but that is the basics. I know the compiler will just make a function for each, i.e.
identity(5);
identity("5");
//generates the functions
int identity(int i) { ... return i; };
const char* identity(const char* i) { ... return i; };
At run-time, which one is faster? And do they have a compile time difference?
Since this function is meant to be called a lot, I'm more interested in run-time performance, but there also could be a large amount of types to generate the function for, so I'm also interested in which one would be faster at compile-time.
Upvotes: 1
Views: 138
Reputation: 75874
auto identity(auto i)
{
//...
return i;
}
is a shorthand for
template <class T>
auto identity(T i)
{
// ...
return i;
}
which in turn is a shorthand for
template <class T>
T identity(T i)
{
// ...
return i;
}
So no difference whatsoever.
Not applicable to your example, but if you are going to use auto
parameters you need to be aware of some gotchas:
auto
as return typeauto foo(auto a)
Does not mean
// not this
template <class T>
T foo(T a)
The return type will be deduced from the return expression(s) in foo
definition, just like any auto
return type. It just happens that in your function the return type is deduced to be the same as the parameter type.
auto
parametersvoid foo(auto a, auto b)
Is not equivalent to
// not this
template <class T>
void foo(T a, T b)
but with
template <class T, class U>
void foo(T a, U b)
Upvotes: 5