我正在编写一个存储具有 X、Y、Z 坐标的点的类,其中对点的特定定义进行了模板化:
template<class T>
class Foo {
void add_point(T point);
}
我类的一些函数需要访问 X、Y、Z 组件。问题是点类型(由第 3 方库定义)没有任何通用接口(interface)来访问坐标。其中一些允许 operator[]
或 operator()
,其他通过 .x
或 .x()
访问.
哪种方法更适合解决这个问题?我应该添加另一个带有访问坐标功能的模板参数吗?还是我应该放弃并以我喜欢的格式保留 3D 点的内部拷贝?
最佳答案
创建一个模板函数类,其工作是统一所有类型点之间的接口(interface)。
像这样:
#include <iostream>
// One kind of point
struct PointA
{
double& operator[](int which) {
return data[which];
};
double data[3];
};
// Another kind of point
struct PointB {
double& x() { return data[0]; }
double& y() { return data[1]; }
double& z() { return data[2]; }
double data[3];
};
// An object which homogenises interfaces
template<class Point>
struct get_coordinate {
double& x() const {
return get_x(p);
}
Point& p;
};
// some overloads
double& get_x(PointA& p) {
return p[0];
}
double& get_x(PointB& p) {
return p.x();
}
template<class Point>
struct Foo
{
void add_point(Point point) { p = point; }
double& x() {
// call through the homogeniser
return get_coordinate<Point>{p}.x();
}
Point p;
};
// test
int main()
{
Foo<PointA> fa;
fa.add_point(PointA{{1,2,3}});
std::cout << fa.x() << std::endl;
Foo<PointB> fb;
fb.add_point(PointB{{1,2,3}});
std::cout << fb.x() << std::endl;
}
关于c++ - 点容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43321018/