c++ - 点容器

标签 c++ templates

我正在编写一个存储具有 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/

相关文章:

C++ 3D 角速度

c++ - 带有 boost::fast_pool_allocator 的模板模板参数

c++ - Boost.MPL 随状态变换?

C++ 模板、静态方法和构造函数

c++ - 模板参数类型推导在函数对象中不起作用

c++ - 有没有办法不等待 system() 命令完成? (在三)

c++ - 为什么 FFMPEG 适用于 1080p 但不适用于 720p 尺寸……(包含代码)

c++ - make_shared 和 emplace 函数

c++ - 如何同步 2 个或更多监视文件夹

c++ - C++中 "typename"的用途是什么