How to prevent a template class from being derived more than once?

前端 未结 4 1944
礼貌的吻别
礼貌的吻别 2021-02-05 07:47

I have the following template class:

template
class T : public I
{
    // ...
};

This template class need to be derived once (an

4条回答
  •  庸人自扰
    2021-02-05 08:21

    I'm not a big fan of macros but if using macros is not a problem to you - you could use a simple and compact solution as follows:

    #include 
    
    template 
    struct prohibit_double_inheritance { };
    
    #define INHERIT(DERIVING, BASE) \
        template<> struct prohibit_double_inheritance { };\
        struct DERIVING: BASE
    
    
    template
    struct T: I
    {
        // ...
        static void do_something() {
            std::cout << "hurray hurray!" << std::endl;
        }
    };
    
    struct U { };
    struct V { };
    
    INHERIT(A, T) {
    };
    
    //INHERIT(B, T) { // cause redetinition of the struct 
    //};                 // prohibit_double_inheritance> 
    
    int main() {
        A::do_something();
    }
    

    [live demo]

提交回复
热议问题