在我继续探索模板的过程中,我不仅根据它拥有的 ItemType 还根据确定它应该如何排序项目的 Functor 参数来模板化我的 Container 类。到目前为止,还不错。
当我想将一个 Container 的内容复制到另一个时,我遇到了一个小问题:如果两个 Container 具有不同的 Functor 类型,那么它们在技术上是不相关的类。因此,不允许容器 A 访问容器 B 的非公开内容。除了将我需要访问的所有内容公开之外,有没有什么好的方法来处理这个问题?也许是某种模板化“ friend ”声明的方法?
演示问题的示例代码如下:
#include <stdio.h>
class FunctorA {};
class FunctorB {};
template <class ItemType, class Functor> class MyContainer
{
public:
MyContainer() : _metaData(0) {/* empty */}
template<class RHSFunctor> void CopyFrom(const MyContainer<ItemType, RHSFunctor> & copyFrom)
{
_metaData = copyFrom._metaData;
_item = copyFrom._item;
}
private:
int _metaData;
ItemType _item;
};
int main(int argc, char ** argv)
{
MyContainer<void *, FunctorA> containerA;
MyContainer<void *, FunctorB> containerB;
containerA.CopyFrom(containerB); // error, containerA::CopyFrom() can't access containerB's private data!
return 0;
}
最佳答案
您可以制作一个仅在 ItemType 上模板化的基本模板类,将数据保留在那里,拥有完整的 2-args 模板子类,并将拷贝放在基类中,因为它不依赖于仿函数无论如何。即:
template <class ItemType> class MyContainerBase
{
public:
MyContainerBase() : _metaData(0) {/* empty */}
void CopyFrom(const MyContainerBase<ItemType> & copyFrom)
{
_metaData = copyFrom._metaData;
_item = copyFrom._item;
}
protected:
int _metaData;
ItemType _item;
};
template <class ItemType, class Functor> class MyContainer:
public MyContainerBase<ItemType>
{
// whatever you need here -- I made the data above protected
// just on the assumption you may need to access it here;-)
};
关于c++ - 有没有办法访问同一类模板的不同实例化的私有(private)部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1191944/