1

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.

AGheller
  • 23
  • 2

1 Answers1

1

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?.

Jason
  • 36,170
  • 5
  • 26
  • 60
  • Thanks for your help. The solution you provide works, but now I think I am completely wrong in trying to use templates to solve my problem. With the template my code must be completely visible to the compiler, so the d-pointer no longer has any reason to exist. I can't have problems with binary compatibility. – AGheller Apr 08 '22 at 07:47
  • @AGheller Perhaps your code does not have to be completely visible. As soon as your template is instantiated with the used classes once (e.g. in the library), you only need the function declaration or the class definition (header) for further using it. Alternatively you could abstract your interfaces at some point, e.g. derive from a non-templated baseclass. We would need more information how the TNode and TLink interact and how many of those classes there are and where they are determined and what code can be visible. – Sebastian Apr 08 '22 at 08:00
  • @AGheller Feel free to ask a separate question for your follow up question by providing sufficient details in that question. – Jason Apr 08 '22 at 08:01