Is there an advantage to the pimpl idiom with pattern?

As far as I understand, the main advantage of the pimpl idiom is hiding data elements in the implementation file instead of the header. However, templates must be fully defined in the header so that the compiler can create them on demand. In this case, is there any advantage of using the pimpl idiom for the template class?

+4
source share
5 answers

While the pimpl idiom doesn't actually hide anything when used in a template, it allows you to easily write non-throwing swaps (although with C ++ 11 movement semantics this is not a concern).

+5
source

In large projects, single translation units are reason enough for pimpl. This works even with templates:

// main interface template <typename> struct MyImpl; class TheInterface { MyImpl<int> * pimpl; }; 

 // implementation #include "MyImpl.hpp" // heavy-weight template library // TheInterface implementation 
+1
source

This is one case that cannot be a strictly idiom, but is similar enough to know about it. That is, to have a type template wrapper through a non-type version.

 class MapBase { public: void* getForKey(const std::string & k); void setForKey(const std::string & k, void * v); ... }; template<typename T> class MyMap { public: T* getForKey(const std::string &k) { return (T*)base_.getForKey(k); } void setForKey( const std::string &k, const T* v) { base_.setForKey(k, T*v); } private: MapBase base_; }; 

Now, any use of MyMap<T> should not be exposed to the internal properties of MapBase, and you get only one implementation of these functions. I would also consider making MapBase an abstract base class to make the decoupling even stronger.

As I said, this is not exactly a simplex, but it solves the same problems the same way.

+1
source

I think if you expand the idiom a little, in some cases you can get at least a little. In the template, not every operation must necessarily depend on the template parameters. So you can inherit from the Impl class, which itself uses the pimpl idiom, something like this:

 struct FooPimpl; class FooImpl { protected: FooPimpl* pimpl; public: void myCommonInterfaceMethod(); }; template <typename T> class Foo : public FooImpl { // stuff that depends on T }; 

Of course, this is highly dependent on the circumstances. But I see that the pimpl idiom works in the context of a template class.

0
source

it is still quite applicable - consider an automatic or generic pointer, which is a template and is quite applicable for solving and implementing PIMPL. regardless of whether it depends on the decision.

templates must be fully defined in the header so that the compiler can create them on demand.

you can declare the members of the template and interface, and then in your cpp type file, you can #include find the necessary specialization definitions and use them there.

0
source

All Articles