Pregunta

template <class T>
class Foo {
public:
    T val;
    Foo(T _v): val(_v){}
    friend ostream& operator<< (ostream& out, const Foo& A) {
        out << A.val;
        return out;
    }
};

template <class X, class Y> Foo<???> operator+(const Foo<X>& A, const Foo<Y> & B) {
    if (sizeof(X) > sizeof (Y))
        return Foo<X>(A.val + B.val);
    else
        return Foo<Y>(A.val + B.val);
}

int main() {
    Foo<double> a(1.5);
    Foo<int> b(2);
    cout << a << endl;
    cout << b << endl;
    cout << a+b << endl;
}

My goal is to have the operator+ function to return different type based on types of the arguments.

For example, if a is int and b is int then return Foo<int>, if one or both of them are double then return Foo<double>.

Is it possible to do?

¿Fue útil?

Solución 2

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

Otros consejos

(C++11): Use a declval expression inside dectype:

#include <utility>

template <class X, class Y> 
Foo<decltype(std::declval<X>() + std::declval<Y>())> operator+(...);

Yes ! Here is the way if you want to give your own rules:

template <typename X, typename Y> struct Rule {};
template<> struct Rule<int, int> { typedef int type;};
template<> struct Rule<float, int> { typedef bool type;};

Then

template <class X, class Y> Foo<typename Rule<X, Y>::type> operator+(...)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top