This is possible (in C++03 or C++11) using partial template specializations.
// C++ does not allow partial specialization of function templates,
// so we're using a class template here.
template <typename X, typename Y, bool xLarger>
struct DoPlusImpl // When x is selected
{
typedef Foo<X> result_type;
};
template <typename X, typename Y>
struct DoPlusImpl<X, Y, false> // When y is selected
{
typedef Foo<Y> result_type;
};
template <typename X, typename Y> // Select X or Y based on their size.
struct DoPlus : public DoPlusImpl<X, Y, (sizeof (X) > sizeof (Y))>
{};
// Use template metafunction "DoPlus" to figure out what the type should be.
// (Note no runtime check of sizes, even in nonoptimized builds!)
template <class X, class Y>
typename DoPlus<X, Y>::result_type operator+(const Foo<X>& A, const Foo<Y> & B) {
return typename DoPlus<X, Y>::result_type
(A.val + B.val);
}
You can see this in action on IDEOne here -> http://ideone.com/5YE3dg