Hide class type in header

后端 未结 2 1829
既然无缘
既然无缘 2021-01-22 00:40

I\'m not sure if this is even possible, but here goes:

I have a library whose interface is, at best, complex. Unfortunately, not only is it a 3rd-party library (and far

相关标签:
2条回答
  • 2021-01-22 01:15

    Essentially, you need a separate set of headers for each use. One that you use to build your DLL and one with only the exported interfaces, and no mention at all of the encapsulated objects. Your example would look like:

    class Node
    {
    public:
        String GetName();
    };
    

    You can use preprocessor statements to get both versions in the same physical file if you don't mind the mess.

    0 讨论(0)
  • 2021-01-22 01:23

    Use the Pimpl (pointer to implementation) idiom. As described, OverlyComplicatedNodeClass is an implementation detail as far as the users of your library are concerned. They should not have to know the structure of this class, or even it's name.

    When you use the Pimpl idiom, you replace the OverlyComplicatedNodeClass pointer in your class with a pointer to void. Only you the library writer needs to know that the void* is actually a OverlyComplicatedNodeClass*. So your class declaration becomes:

    class Node
    {
    public:
        String GetName();
    
    private:
        void * impl; 
    };
    

    In your library's implementation, initialize impl with a pointer to the class that does the real work:

    my_lib.cpp

    Node::Node()
    : impl(new OverlyComplicatedNodeClass)
    {
    // ...
    };
    

    ...and users of your library need never know that OverlyComplicatedNodeClass exists.

    There's one potential drawback to this approach. All the code which uses the impl class must be implemented in your library. None if it can be inline. Whether this is a drawback depends very much on your application, so judge for yourself.

    In the case of your class, you did have GetName()'s implementation in the header. That must be moved to the library, as with all other code that uses the impl pointer.

    0 讨论(0)
提交回复
热议问题