通常,适配器的目的是以修改后的格式进行函数调用。有没有办法对成员变量做同样的事情?也就是说,假设我有一个包含 SomePoint
的对象和另一个包含 DifferentPoint
的对象。 SomePoint
将其数据存储为大写的成员变量 X
和 Y
其中 AnotherPoint
将其数据存储为小写的成员变量 x
和 x
。所以问题是你不能写一个接受 SomePoint
或 DifferentPoint
的函数,因为你不能访问 .x
或.X
(即使使用模板而不完全专门针对每个不同的点类型,在这种情况下,您也可以只重载点类型)。
问题是有没有一种方法可以让适配器在请求 .x
时为 SomePoint
生成 .X
?这两种点类型都是库类,所以我不能直接编辑其中任何一种的内部结构。我还想避免复制数据。
最佳答案
通常的做法是写一个 traits 类来指定如何取出你想要的数据。
这是使用指向成员的指针的可能实现。如果愿意,您可以将它们变成函数或 lambda。
template <typename T>
struct PointTraits;
template <>
struct PointTraits<SomePoint> {
constexpr static auto getX = &SomePoint::x;
constexpr static auto getY = &SomePoint::y;
};
template <>
struct PointTraits<AnotherPoint> {
constexpr static auto getX = &AnotherPoint::X;
constexpr static auto getY = &AnotherPoint::Y;
};
然后你会像这样使用它:
template <typename PointT>
void printX (const PointT& point) {
std::cout << point.*PointTraits<T>::getX;
}
关于c++ - "Adapter"为成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725228/