Which return type declare when using two templates?

Sorry for my probably wrong title, i don't know how to call it properly.

I've got a function that has two parametrs. These parapetrs are templates.
If 1st parametr is bigger or equal to 2nd parametr it's returned. Otherwise 2nd one is returnd. How to write declaration of this function?

Maby something like this?
1
2
  template <typename T1, typename T2>
  auto Bigger(T1, T2) -> if(T2 > T1) T2 else T1;


Thanks in advance
You can use the ternary conditional operator, which will find the common type for you (or you can use std::common_type, but that's just using the ternary operator indirectly)

C++14:
1
2
3
4
5
template <typename T1, typename T2>
auto Bigger(T1 a1, T2 a2)
{
    return a2 > a1 ? a2 : a1;
}
http://coliru.stacked-crooked.com/a/ef4abfc849fc724b

or C++11
1
2
3
4
5
6
template <typename T1, typename T2>
auto Bigger(T1 a1, T2 a2) -> typename std::common_type<T1, T2>::type
{
   if(a2 > a1) return a2; else return a1;
   // or just return a2 > a1 ? a2 : a1;
}


PS: constexpr would be nice too
Last edited on
Thanks for reply.

1st suggestion doesn't work on VS 2013. Maybe I don't have C++14 enabled.

2nd suggestion kind of works. If I write "std::cout << Bigger(10, 'c')" function returns char as int (it returns code of 'c' letter, 99). Any ideas to make it work better? If no thanks for what you wrote already.

EDIT
I cheked coliru.stacked and on their site 1st option also returns int instead of char;
Last edited on
A function can return only one type. (This is important as you need to know how to generate code before function call). So the return type is deduced as common (one which can hold values of both types).

If you need to return two types, you will need to use something more complex.
Like saving actual type (typeid or similar) alongside return value.

One way is to use Boost::Variant:

1
2
3
4
5
6
7
8
#include <boost/variant.hpp>
//...
template <typename T1, typename T2>
auto Bigger(T1 a1, T2 a2) -> boost::variant<T1, T2>
{
   if(a2 > a1) return a2; else return a1;
   // or just return a2 > a1 ? a2 : a1;
}
http://coliru.stacked-crooked.com/a/991948978dda183e
Last edited on
Thank you, it works.
Topic archived. No new replies allowed.