在 c++ 中包装来自不同库的自定义类型

Wrap custom types from different libraries in c++

本文关键字:自定义 类型 c++ 包装      更新时间:2023-10-16

当使用不同的库时,我总是发现每个库都有相同的"真实单词实体"的自定义类型。

假设我有一个使用 3 维点的项目,我只使用 OpenCv 和 PCL(点云库)的算法。我发现自己有这些类型

  • OpenCv Point3_
  • 用于 PCL 的 PointXYZ
  • Point3d 我的自定义类型

现在我有了为 Point3d 编写的算法,但我也想使用这些库中的算法。将大集合中的每个点从一种类型来回转换为另一种类型需要内存和时间。

围绕此进行某种抽象的最佳方法是什么?

你可以做这样的事情

template<class T>
    struct Getter{
};
template<class T>
struct Getter<Point3_<T>>{
     typedef T& type;
     static type getx(Point3_<T>& p){
         return p.x;
     }
};
template<>
struct Getter<PointXYZ>{
     typedef float& type;
     static type getx(PointXYZ& p){
         return p.x;
     }
};
template <class T>
point_x(T& p) -> Getter<T>::type{
      return Getter<T>::getx(p);
}

对 y 和 z 执行相同的操作然后修改您的算法以采用模板,而不是使用 p.x = ...用

getx(p) = ..
auto x = getx(p)