How do you declare an interface in C++?

前端 未结 15 2613
借酒劲吻你
借酒劲吻你 2020-11-22 03:26

How do I setup a class that represents an interface? Is this just an abstract base class?

15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 04:09

    While it's true that virtual is the de-facto standard to define an interface, let's not forget about the classic C-like pattern, which comes with a constructor in C++:

    struct IButton
    {
        void (*click)(); // might be std::function(void()) if you prefer
    
        IButton( void (*click_)() )
        : click(click_)
        {
        }
    };
    
    // call as:
    // (button.*click)();
    

    This has the advantage that you can re-bind events runtime without having to construct your class again (as C++ does not have a syntax for changing polymorphic types, this is a workaround for chameleon classes).

    Tips:

    • You might inherit from this as a base class (both virtual and non-virtual are permitted) and fill click in your descendant's constructor.
    • You might have the function pointer as a protected member and have a public reference and/or getter.
    • As mentioned above, this allows you to switch the implementation in runtime. Thus it's a way to manage state as well. Depending on the number of ifs vs. state changes in your code, this might be faster than switch()es or ifs (turnaround is expected around 3-4 ifs, but always measure first.
    • If you choose std::function<> over function pointers, you might be able to manage all your object data within IBase. From this point, you can have value schematics for IBase (e.g., std::vector will work). Note that this might be slower depending on your compiler and STL code; also that current implementations of std::function<> tend to have an overhead when compared to function pointers or even virtual functions (this might change in the future).

提交回复
热议问题