首页 > 解决方案 > C++中模板的继承?

问题描述

假设我想用两个新的访问器编写一个泛型类Point和一个专用类:和. 在 Python 中,我可能会写这样的东西:Point2DgetX()getY()

class Point(list):
    def __init__(self, *args):
        list.__init__(self, args)

    def __add__(self, other):
        return type(self)(*[a + b for a, b in zip(self, other)])

    def __str__(self):
        return 'P(' + repr(self)[1:-1] + ')'

class Point2D(Point):
    @property
    def get_x(self):
        return self[0]

p = Point2D(1,2,3)
q = Point2D(3,4,5)
c = p + q
print(f"{c} = {p} + {q}")
print(c.get_x)

但是在 C++ 中。我发现模板继承很麻烦。cigien提到了 CRTP 模式,所以我写了这个:

#include <algorithm>
#include <array>
#include <iostream>

using namespace std;

template <typename C, typename T, int N>
class PointCRTP
{
   protected:
    array<T, N> elements;

   public:
    PointCRTP() = default;
    PointCRTP(array<T, N> el) : elements(el) {}

    C operator+(C& other)
    {
        C c;
        transform(elements.begin(), elements.end(), other.elements.begin(),
                  c.elements.begin(), plus<int>());
        return c;
    }

    T operator[](int k) { return elements[k]; }

    friend std::ostream& operator<<(std::ostream& os, C const& x)
    {
        os << "P(";
        for (auto k : x.elements) os << k << ", ";
        return os << "\b\b" << ')';
    }
};

template <typename T, int N>
struct Point : public PointCRTP<Point<T, N>, T, N> {
    using PointCRTP<Point<T, N>, T, N>::PointCRTP;
};

template <typename T>
struct Point2D : public PointCRTP<Point2D<T>, T, 2> {
    Point2D() = default;
    Point2D(T x, T y) : PointCRTP<Point2D<T>, T, 2>({x, y}) {}

    T getX() { return PointCRTP<Point2D<T>, T, 2>::elements[0]; }
    T getY() { return PointCRTP<Point2D<T>, T, 2>::elements[1]; }
};

int main()
{
    Point<int, 3> p({1, 2, 3});
    Point<int, 3> q({3, 4, 2});
    Point<int, 3> c = p + q;
    std::cout << c << " = " << p << " + " << q << endl;

    Point2D<int> r(1, 2);
    Point2D<int> s(3, 4);
    Point2D<int> t = r + s;
    std::cout << t << " = " << r << " + " << s << endl;
}

我不是很高兴有几个原因:

我将如何改善这一点?

标签: pythonc++ooptemplatesinheritance

解决方案


推荐阅读