Search code examples
c++boostboost-asiopimpl-idiom

Is it possible to wrap boost sockets with Pimpl?


in a project we want to wrap the Boost Asio socket in a way, that the using class or the wrapping .h does not have to include the boost headers.

We usually use pointers and forward declarations for wrapped classes.

Foward declaration:

namespace boost
{
  namespace asio
  {
    namespace ip
    {
      class udp;
    }
  }
}

And then declaring the socket:

  scoped_ptr<boost::asio::ip::udp::socket> socket_;
  scoped_ptr<boost::asio::ip::udp::endpoint> receiveEp_;

(If you don't know scoped_ptr, ignore it, the problem is equal with a standard * pointer.)

But this gives a compiler error:

error C2027: use of undefined type 'boost::asio::ip::udp'

I understand this is because udp is actually not a namespace, but a class itself. We only want to use the inner class though, any ideas?


Solution

  • With inner types your only option is wrapping everything. Hide scoped pointers themselves inside a forward declared class. Users would see only your API and pass around your own objects instead of boost objects.

    In your example though scoped_ptr look like private member declarations, you can get away with simple:

    // header
    class SomeClass 
    { 
    public:
        SomeClass();
        // stuff   
    private: 
        scoped_ptr<class pimpl_bla> _m; 
    };
    
    // source
    class pimpl_bla
    {
    public: 
        scoped_ptr<boost::asio::ip::udp::socket> socket_;
    };
    
    SomeClass::SomeClass() 
        :_m(new pimpl_bla)
    { 
    }