vendredi 8 mai 2015

Choose between template function and auto type deduction

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 ?

Aucun commentaire:

Enregistrer un commentaire