Cirvis
Cirvis

Reputation: 398

creating template function with different parameters

So for example I want to create a function that add two numbers and return total.

template<typename T1, typename T2>
T1 add( T1 n1, T2 n2 ){
    return n1 + n2;
}

Problems is if T1 is int and T2 is float. Then function will return int. But I want it to return float. Is there a trick or a way to achieve it?

Upvotes: 1

Views: 123

Answers (4)

Uroc327
Uroc327

Reputation: 1429

Another C++11 solution would be to use std::common_type<T1, T2>::type as return type.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

If you are using C++14:

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

This is like the C++11 version, but does not require you to write out the trailing-return-type yourself (which is nice).

Upvotes: 3

KoKuToru
KoKuToru

Reputation: 4115

If you are using C++11

decltype is your friend

template<typename T1, typename T2>
auto add( T1 n1, T2 n2 ) -> decltype(n1 + n2) {
    return n1 + n2;
}

This will use the type resulting from n1 + n2

More at http://en.wikipedia.org/wiki/C%2B%2B11#Alternative_function_syntax

Upvotes: 10

ravi
ravi

Reputation: 10733

Yes

template<typename RT, typename T1, typename T2>
RT add( T1 n1, T2 n2 ){
    return n1 + n2;
}

Now call it like:-

add<float>(2,3.0);

Upvotes: 4

Related Questions