Template class with dpointer

Viewed 54

I am trying to use the dpointer pattern in a generic class that made use of template but I cant figure how to define it correctly.

template <class TNode, class TLink>
class Network
{
private:
    template<class TNode, class TLink>
    struct Impl<TNode,TLink>;
    std::unique_ptr<Impl<TNode,TLink>> d_ptr;   //d_pointer
};

How can I define the Impl class in the cpp file?

template<class TNode, class TLink>
struct Network<TNode,TLink>::Impl<TNode, TLink>
{
     vector<TNode> nodes;
     vector<TLink> links;
}

This doesn't work! It says that Impl is not a template error C3856.

1 Answers

The correct way to do this would be to use different names for the template parameters of the nested class template Impl from the names of the template parameters already used for the containing class template Network, as shown below:

template <class TNode, class TLink>
class Network
{
private:
//-----------------v--------v--------------->use different names 
    template<class T, class P>
    struct Impl;
    std::unique_ptr<Impl<TNode,TLink>> d_ptr;   //d_pointer
};
template<class TNode, class TLink>
//-------------v--------v------------------->use different names 
template<class T, class P>
struct Network<TNode,TLink>::Impl
{
     std::vector<TNode> nodes;
     std::vector<TLink> links;
};

Also refer to Why can templates only be implemented in the header file?.

Related