The mechanics of extension via free functions or member functions

后端 未结 5 954
挽巷
挽巷 2021-02-14 12:45

Loads of C++ libraries, the standard included, allow you to adapt your objects for use in the libraries. The choice is often between a member function or a free function in the

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-14 12:55

    If I understood correctly your problem is simply solved using (maybe multiple) inheritance. You have somewhere a namespace free function:

    namespace NS {
    void DoSomething()
    {
        std::cout << "NS::DoSomething()" << std::endl;
    }
    } // namespace NS
    

    Use a base class which forwards the same function:

    struct SomethingBase
    {
        void DoSomething()
        {
            return NS::DoSomething();
        }
    };
    

    If some class A deriving from SomethingBase does not implement DoSomething() calling it will call SomethingBase::DoSomething() -> NS::DoSomething():

    struct A : public SomethingBase // probably other bases
    {
        void DoSomethingElse()
        {
            std::cout << "A::DoSomethingElse()" << std::endl;
        }
    };
    

    If another class B deriving from SomethingBase implement DoSomething() calling it will call B::DoSomething():

    struct B : public SomethingBase // probably other bases
    
    {
        void DoSomething()
        {
            std::cout << "B::DoSomething()" << std::endl;
        }
    };
    

    So calling DoSomething() on an object deriving from SomethingBase will execute the member if existing, or the free function otherwise. Note that there is nothing to throw, you get a compile error if there is no match to your call.

    int main()
    {
        A a;
        B b;
        a.DoSomething(); // "NS::DoSomething()"
        b.DoSomething(); // "B::DoSomething()"
        a.DoSomethingElse(); // "A::DoSomethingElse()"
        b.DoSomethingElse(); // error 'DoSomethingElse' : is not a member of 'B'
    }
    

提交回复
热议问题