I have a generic question about template functions versus auto type deduction for functions.
For years, we have have been able to write template function :
template <class T> T add(T a,T b){
return a+b;
}
There is a TS for using auto for function's parameters deduction
auto add(auto a,auto b){
return a+b;
}
I though with auto, one had no way to get to the actual type and for instance use static members, but this works just fine :
#include <iostream>
struct foo
{
static void bar(){std::cout<<"bar"<<std::endl;}
static int i ;
};
int foo::i{0};
void t(auto f){
decltype(f)::bar();
std::cout<< decltype(f)::i<<std::endl;
}
int main(int argc, char *argv[])
{
t(foo());
return 0;
}
So is there any reason to choose one instead of the other ?
The obvious reason for this particular code would be that they don't really have the same semantics at all.
In particular, if you pass arguments of different types, the version using auto will deduce a type independently for each, then based on those deduce a type for the result.
Conversely, with the template version, you've specified exactly one type, so the arguments must both be the same type (and the result will be the same).
So, to get the code to be more nearly equivalent, you'd really need to write the template more like:
template <class T, class U>
auto add(T a, U b) -> decltype(a+b) {
return a+b;
}
This is obviously possible as well, but adds even more strength to the arguments in favor of using auto instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With