dimanche 2 mai 2021

Alternate way of specifying the return type of a function template(Without using explicit template argument)

Hi i am curious about an alternate way of specifying the return type of a function template. Note that i know for this purpose we can use explicit template arguments(ETA from now on) and specifying the return type of a function template is one of the reason why ETA was introduced or used atleast. I have written the example code below which shows we can use function pointer to specify the return type of the function template. My question is which of these 2 methods is better(in any way) and is my use of function pointers correct or is there anything wrong with the code? Is there any limitation of function pointer method which can only be solved by ETA method?

#include <iostream>

template<typename T1, typename T2, typename T3> T1 func(T2 l, T3 m){
    std::cout<<"Inside function template func"<<std::endl;
    T1 k = l * m;
    return k;
}

int main(){
    float arg1 = 3.4,arg2 = 5.2;
    auto p = func<int>(arg1, arg2);// THIS USES **ETA**
    std::cout<<"this  is the result calculated using explicit template argument, p is: "<<p<<std::endl;
    int (*p1)(float, float) = func;// THIS USES function pointer
    auto new_p = p1(arg1, arg2);
    std::cout<<"this is the result calculated using function pointers, new_p is: "<<new_p<<std::endl;
    
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire