Hide class type in header

后端 未结 2 1830
既然无缘
既然无缘 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: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.

提交回复
热议问题