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

前端 未结 4 1937
礼貌的吻别
礼貌的吻别 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:22

    Since you mention that it's okay to pass A, B and C to T then how about this runtime solution?

    #include 
    #include 
    
    //This class will check to see each T is only instantiated with a unique Y
    template 
    struct T_helper
    {
        template 
        static void check()
        {
            if(derived_type)
                assert(*derived_type == typeid(Y));
            else
                derived_type = &typeid(Y);
        }
        static const std::type_info * derived_type;
    };
    
    template 
    const std::type_info * T_helper::derived_type = nullptr;
    
    template 
    struct T
    {
        T()
        {
            T_helper::template check();
        }
    };
    
    struct A : T {};
    struct B : T {};
    
    int main()
    {
        A a1, a2, a3; // These are all okay
        B b1;         // This one will trigger the assert
    }
    

提交回复
热议问题