最佳方法声明为朋友类模板不知道一个模板参数

问题描述 投票:0回答:1

我偶然到一个场景,我试图找出了最干净的方法,如果有任何。

我有一个受保护的构造,需要的朋友模板类实例化一个模板类。模板参数两者份额的一部分,但不是全部。这里是我的问题的一个例子。

我希望从有经验的程序员知道是否还有其他可能的解决方案(我想没有,除了转向构造函数public),如果两者之间我提出了一个比另一个更容易接受。谢谢

方案1 - 我提供“不必要的”模板参数与受保护的构造(类Element)的类。

template <typename Tp_>
class Engine_Type_X
{
};
template <typename Tp_>
class Engine_Type_Z
{
};

//Forward declaration
template <typename Tp_, template<typename> typename Eng_>
class Container;

//Eng_ is only required to declare the friend class
template <typename Tp_,template<typename> typename Eng_> 
class Element
{
    friend class Container<Tp_,Eng_>;

    Tp_ tp_;
protected:  
    Element(Tp_ tp) : tp_{tp}   //protected ctor!!!
    {}
};

template <typename Tp_, template<typename> typename Eng_>
class Container
{
    using Element_tp = Element<Tp_,Eng_>;
    using Engine_tp  = Eng_<Tp_>;

    std::vector<Element_tp> container_;
    Engine_tp               &engine_;

public:
    Container(Engine_tp &engine) : container_{},engine_{engine}
    {}

    void install(Tp_ tp)
    {   Element_tp elem{tp};
        container_.emplace_back(elem);        
    }
};

解决方案2 - 我用像我在这里找到How to declare a templated struct/class as a friend?的方法

template <typename Tp_>
class Engine_Type_X
{
};
template <typename Tp_>
class Engine_Type_Z
{
};

template <typename Tp_>
class Element
{
    template<typename,template<typename>typename> friend class Container; //All templated classes are friend

    Tp_ tp_;
protected:  
    Element(Tp_ tp) : tp_{tp}   //protected ctor!!!
    {}
};

template <typename Tp_, template<typename> typename Eng_>
class Container
{
    using Element_tp = Element<Tp_>;
    using Engine_tp  = Eng_<Tp_>;

    std::vector<Element_tp> container_;
    Engine_tp               &engine_;

public:
    Container(Engine_tp &engine) : container_{},engine_{engine}
    {}

    void install(Tp_ tp)
    {   Element_tp elem{tp};
        container_.emplace_back(elem);        
    }
};
c++ templates friend
1个回答
0
投票

你还有一些选项来探索。

  1. 你可以做一个类的内部类(称为嵌套类),这将自动将其朋友的“外部”类。见qazxsw POI
  2. 另一种方法是需要一个所谓的“令牌”作为参数的构造函数,此令牌类型通常不采取模板参数,然后让这个这个令牌只能由其他类来创建(可能是嵌套键入或friended)。

从OP请求,这里是一种方式的轮廓来完成2.选项:(使用的C ++ 0x)

https://en.cppreference.com/w/cpp/language/nested_types
© www.soinside.com 2019 - 2024. All rights reserved.