1

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?

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

4

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);

1 Comment

What would be syntax for arithmetic operators?
3

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).

2 Comments

Why not decltype(auto)? add should return a reference if operator+ for two types returns one
@Columbo: I confess I know relatively little about this stuff. Please feel free to suggest an appropriate remedy.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.