在模板中重载默认类型的运算符

时间:2018-04-21 11:14:39

标签: c++ templates operator-overloading

我如何为每个期望的类型重载模板类中的运算符 - 例如int和char。

    Point<char> operator+ (Point<char> const& sec){
        Point<char> tmp(x+2, y+3);
        return tmp;
    }


    Point<int> operator+ (Point<int> const& sec){
        Point<int> tmp(x+sec.x + 1, y+sec.y + 1);
        return tmp;
    }

    Point<T> operator+ (Point<T> const& sec){
        return Point<T>(x+sec.x, y+sec.y);
    }

这样的事情并不奏效。我可以为特定类型或T重载,但不能将两者结合起来。

3 个答案:

答案 0 :(得分:2)

你可以明确地专门化之外的类,就像这样(最小例子):

#include <iostream>

template<class T>
struct Point
{
    Point operator+(Point rhs)
    {
        std::cout << "Generic\n";
        return rhs;
    }
};

template<>
Point<char> Point<char>::operator+(Point<char> rhs)
{
    std::cout << "char\n";
    return rhs;
}

template<>
Point<int> Point<int>::operator+(Point<int> rhs)
{
    std::cout << "int\n";
    return rhs;
}


int main()
{
    Point<double> p;
    Point<int> i;
    Point<char> c;

    p + p;
    i + i;
    c + c;
}

Live on Coliru

答案 1 :(得分:0)

您可以添加if语句,如

Error in match.arg(method) : 'arg' must be NULL or a character vector

将此内容写入Point运算符+(){}的代码中。

我从未实现过这个,但我认为你可以让它发挥作用。

我不知道操作员是否可以按照您想要的方式重载,但您可以试试这个。

答案 2 :(得分:0)

要明确专门化成员,您还需要明确专门化其周围的类模板。在您的情况下,您可以使用朋友:

template <class T>
class Point {
public:
    Point(T x, T y) : x(x), y(y) {}

private:
    T x, y;

    friend Point<char> operator+ (Point<char> const& a, Point<char> const& b);
    friend Point<int> operator+ (Point<int> const& a, Point<int> const& b);
    template<class T>
    friend Point<T> operator+ (Point<T> const& a, Point<T> const& b);
    template<class T>
    friend Point<T*> operator+ (Point<T*> const& a, Point<T*> const& b);
};

Point<char> operator+ (Point<char> const& a, Point<char> const& b) {
    std::cout << "overload for char" << std::endl;
    return a;
}


Point<int> operator+ (Point<int> const& a, Point<int> const& b) {
    std::cout << "overload for int" << std::endl;
    return a;
}

template <class T>
Point<T> operator+ (Point<T> const& a, Point<T> const&) {
    std::cout << "overload for other non-pointers type" << std::endl;
    return a;
}

// you can even provide overload for pointers
template <class T>
Point<T*> operator+ (Point<T*> const& a, Point<T*> const&) {
    std::cout << "overload for pointers" << std::endl;
    return a;
}


int main() {

    Point<int> p1(1,1);
    p1 + p1;
    Point<char> p2(1, 1);
    p2 + p2;
    Point<long long> p3(1, 1);
    p3 + p3;

    int i[2];
    Point<int*> p4(i, i+1);
    p4 + p4;

    return 0;
}
  

int的重载   char过载   其他非指针类型的重载
  指针重载