通常,适配器的目的是以修改的格式进行函数调用.有没有办法为成员变量做同样的事情?也就是说,我有一个包含a的对象SomePoint和另一个包含a的对象DifferentPoint.SomePoint其存储的数据作为成员变量资本X和Y地方AnotherPoint将其存储的数据作为成员变量小写x和x.所以问题是你不能编写一个接受a SomePoint或a 的函数,DifferentPoint因为你无法访问.x或者.X(甚至使用模板而没有完全专门针对每个不同的点类型,在这种情况下你可能只是在点上重载类型).
现在的问题是有没有一种方法,使这将产生一个适配器.X的SomePoint时候.x请求?这两种点类型都是库类,所以我不能直接编辑任何一个的内部.我还想避免复制数据.
通常的方法是编写一个traits类来指定如何获取所需的数据.
这是使用指向成员的可能实现.如果您愿意,可以将它们变成函数或lambdas.
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;
};
Run Code Online (Sandbox Code Playgroud)
然后你会像这样使用它:
template <typename PointT>
void printX (const PointT& point) {
std::cout << point.*PointTraits<T>::getX;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |