テンプレートを使った継続的な冒険では、Containerクラスを、それが保持するItemTypeだけでなく、アイテムの順序を決定するFunctor引数にもテンプレート化しました。ここまでは順調ですね。
あるコンテナの内容を別のコンテナにコピーしたいときに、私が遭遇した小さな問題が発生します。2つのコンテナのFunctorタイプが異なる場合、それらは技術的には無関係のクラスです。したがって、コンテナAはコンテナBの非公開コンテンツにアクセスできません。アクセスするために必要なすべてのものを公開する以外に、この問題に対処するための良い方法はありますか?おそらく、「友達」宣言をテンプレート化する方法はありますか?
問題を示すサンプルコードは次のとおりです。
#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;
}