asmmo
asmmo

Reputation: 7100

Combining multiple templates in each other

How can I combine multiple types in one function like

template < typename T1 >
template < typename T2 >
T2 average( T1 v1, T1 v2, T1 v3 )
{
    T averageValue;
    cout<<"after averageValue; v1: "<<typeid(v1).name()
        <<" v2: "<<typeid(v2).name()
        <<" v3: "<<typeid(v3).name()
        <<" averageValue: "<<typeid(averageValue).name();
    averageValue =(v1+v2+v3)/.3;
    cout<<"\nAfter averageValue =(v1+v2+v3)/3; averageValue: "<<typeid(averageValue).name();
    return averageValue;
};

I know that the code won't compile but I want to know if there is any way to do something like that

Upvotes: 1

Views: 121

Answers (2)

Walter
Walter

Reputation: 45444

In C++17 you can use a variadic template with a fold expression in conjunction with the sizeof... operator:

template<typename... Args>
auto average(Args&&...args)
{
    return (args + ...) / double(sizeof...(args));
}

Upvotes: 3

Kai Guther
Kai Guther

Reputation: 793

You can use multiple template arguments

template< typename T1, typename T2>
T2 average(T1 v1, T1 v2, T1 v3){
// stuff
}

Just make sure to declare averageValue as T2. Of course, this will only work if (v1+v2+v3)/3 is defined and can be converted to T2.

Upvotes: 1

Related Questions