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 がintreturnFoo<int>の場合、一方または両方がdoublereturnの場合Foo<double>です。

することは可能ですか?

4

3 に答える 3

5

(C++11): declvaldectype 内で式を使用します。

#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 に答える