dimanche 28 juin 2020

variadic templates vs using tuples for adding different data pairs in an argument

following main code works fine

    string hello = "Hello ";
    string world = "templates!";

    cout << "var template add: ";


    cout << setprecision(2) <<
        var_template_add(5, 4, 5.5, 4.0);

for following template generator code and variadic func

template <typename T> 
auto add(T a, T b) {
    return a + b;
}


template <typename T, typename... Rest> 
auto var_template_add(T first, T second, Rest... others) {
    return first + second + add (others...);
}

But if added two more string args, like this

var_template_add(5, 4, 5.5, 4.0, hello, world);

is caught by compiler error saying "no matching overloaded function found".

Again,

string hello = "Hello ";
string world = "templates!";
cout << "strings add result: " << setprecision(2) << add(hello, world) << endl;

could work if i write template function "add" like below:

template <typename T1, typename T2>
auto add(T1 a, T2 b) {
    return a + b;
}

My question is, how could i make the line

var_template_add(5, 4, 5.5, 4.0, hello, world);

work without writing another add function like just above?!

please note i could use tuple to pass this values but for now, i just want to keep away. any thoughts/improvements?

Aucun commentaire:

Enregistrer un commentaire