2
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;
}

我的目标是让operator+函数根据参数的类型返回不同的类型。

例如,如果aisint和 b 则为intreturn Foo<int>,如果其中之一或两者为double则 return Foo<double>

有可能吗?

4

3 回答 3

5

declval(C++11):在 dectype 中使用表达式:

#include <utility>

template <class X, class Y> 
Foo<decltype(std::declval<X>() + std::declval<Y>())> operator+(...);
于 2013-07-26T23:58:00.087 回答
3

这可以使用部分模板特化(在 C++03 或 C++11 中)。

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

您可以在 IDEOne 上看到这一点 -> http://ideone.com/5YE3dg

于 2013-07-27T00:03:58.053 回答
1

是的 !如果您想给出自己的规则,可以使用以下方法:

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

然后

template <class X, class Y> Foo<typename Rule<X, Y>::type> operator+(...)
于 2013-07-27T00:06:20.843 回答