What would a CRTP-based solution to this look like?

前端 未结 2 777
南笙
南笙 2020-12-22 01:49

I asked the following question in this post (pasted below for convenience). One of the comments suggested that there is a CRTP-based solution to the problem. I am not able t

2条回答
  •  醉梦人生
    2020-12-22 02:35

    Here is my own first solution. It is not CRTP though and it suffers from a huge drawback as explained at the end of the answer:

    template 
    struct ManagedNode;
    
    // For classes that do not derive
    template <> struct ManagedNode {
        using Base1 = void; using Base2 = void; using Base3 = void;
        using Base4 = void;
    };
    // To avoid inaccessible base
    // See http://stackoverflow.com/q/34255802/2725810
    struct Inter0: public ManagedNode<>{};
    
    // For classes that derive from a single base class
    template 
    struct ManagedNode : public Inter0,
                                                   public Base1_ {
        using Base1 = Base1_;
    };
    // To avoid inaccessible base
    template 
    struct Inter1: public ManagedNode{};
    
    // For classes that derive from two base classes
    template 
    struct ManagedNode : public Inter1,
                                                     public Base2_ {
        using Base2 = Base2_;
    };
    
    // Some user classes for testing the concept
    
    struct A : public ManagedNode<> {
        int data1;
    };
    
    struct B : public ManagedNode<> {};
    
    struct C : public ManagedNode {};
    
    int main() {
        C c;
        std::cout << sizeof(c) << std::endl;
        return 0;
    }
    

    This code produces the output of 12, which means that c contains the data1 member three times! For my purposes this drawback over-weighs the benefits of the reflection that this approach provides. So, does anyone have a suggestion for a better approach?

提交回复
热议问题