python - C++中模板的继承?
问题描述
假设我想用两个新的访问器编写一个泛型类Point
和一个专用类:和. 在 Python 中,我可能会写这样的东西:Point2D
getX()
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;
}
我不是很高兴有几个原因:
- 很麻烦
- 看起来很丑
- 我必须重新定义所有的构造函数
我将如何改善这一点?
解决方案
推荐阅读
- python - 无法访问 Python 2d 数组中的行元素?
- isabelle - 如何对不同模式的归纳谓词使用不同的代码引理?
- google-apps-script - 如何循环遍历问题选项,以便我可以将一个选项指定为正确,而将其他选项指定为不正确?
- ms-access - 微软访问?显示空白返回的通配符
- linux - Bash:比较两个变量中的IP地址
- c++ - C++:错误:“{”标记之前的预期类名
- c++ - 如何告诉 gcc 显示您使用的优化标志列表
- javascript - 如何从没有目的地的给定节点创建路径
- ios - 如何在多个视图中使用来自单例的一个回调
- bash - 查找并打印列值重复 n 次的行