1

I have currently implemented a library using the pImpl idiom as such (just an example);

// library.h

class lib_public_type
{
    class impl;
    std::unique_ptr<impl> impl__;

public:
    void libTypeFunction();
}

// library.cpp
#include "library.h"

class lib_public_type::impl
{
private:
    std::string libVar1;

    void libPrivateFunction1()
    {
        ...
    }

    void libPrivateFunction2()
    {
        ...
    }
}

lib_public_type::libTypeFunction()
{
    libPrivateFunction1();
    libPrivateFunction2();
}

Now I would like to remove as much unneeded information from the header file as possible for another project using a built version of the library. I was wondering if there is a better way of removing the internals from the header of lib_public_type without resorting to maintaining two separate headers?

Would it be possible to do something like;

// library.h
#ifndef PROVIDES_IMPL
    // define as empty string if not already defined
    #define PROVIDES_IMPL 
#endif 

class lib_public_type
{
PROVIDES_IMPL

public:
    void libTypeFunction();
}

// library.cpp
#define PROVIDES_IMPL class impl;\
    std::unique_ptr<impl> impl__;

#include "library.h"

...

Or would this have unwanted consequences for the project using the library?

Thizzer
  • 16,153
  • 28
  • 98
  • 139
  • Not a good idea. The memory signatures of `lib_public_type` with pimpl is different from `lib_public_type` without pimpl. If you pass a `lib_public_type` into the library, like when you call a non-static method, Crom only knows what will happen. – user4581301 Mar 10 '20 at 21:08
  • That's what I was afraid of, any other idioms or solutions you can recommend to get a 'cleaner' header? – Thizzer Mar 10 '20 at 21:23
  • Only completely eliminating the class and replacing it with an opaque object, a handle that represents the class, and a few free functions that get and free a handle and convert the handle to a class instance and invoking the appropriate method on the class. You're probably better off living with the pimpl. – user4581301 Mar 10 '20 at 21:29
  • On the other hand if you're intending to use a shared library, this may be the way to go. You may not be able to guarantee that all users of the library will be using the exact same `std::unique_ptr` implementation. – user4581301 Mar 10 '20 at 21:32

0 Answers0