Is it possible to prevent multiple inheritance of specific base classes at compile time?

前端 未结 2 971
粉色の甜心
粉色の甜心 2021-02-15 15:50

What I am looking to do is develop two different base classes which should not be inherited together in the one derived class. Is there any way I can enforce this at compile tim

2条回答
  •  耶瑟儿~
    2021-02-15 16:29

    An interesting problem. I found a solution that works for Microsoft (R) C/C++ Optimizing Compiler Version 18.00.31101 for x64:

    #include 
    #include 
    using namespace std;
    
    class SuperBase {
    public:
    SuperBase():count(0) {
        cout << "SuperBase constructor..." << endl;
    }
    ~SuperBase() {}
    protected:
    int count;
    };
    class Base1:virtual SuperBase
    {
    public:
    Base1() 
    {
        SuperBase::count++;
        assert(SuperBase::count==1);
        cout << "Base1 constructor..." << endl;
    }
    
    ~Base1() 
    {
        cout << "Base1 Destructor..." << endl;
    }
    };  
    
    class Base2:virtual SuperBase
    {
    public:
    Base2() 
    {
        SuperBase::count++;
        assert(SuperBase::count==1);
        cout << "Base2 constructor..." << endl;
    }
    
    ~Base2() 
    {
      cout << "Base2 Destructor..." << endl;  
    }
    };
    
    class Derived : public Base1, public Base2 
    {
    public:
      Derived()
      {
      cout << "Derived constructor...."  << endl;
      }
      ~Derived()
      {
      cout << "Derived Destructor..." << endl;
       }
    };
    
    class Derived1 : public Base1
    {
    public:
      Derived1()
      {
      cout << "Derived1 constructor...."  << endl;
      }
      ~Derived1()
      {
      cout << "Derived1 Destructor..." << endl;
       }
    };
    class Derived2 : public Base2
    {
    public:
      Derived2()
      {
      cout << "Derived2 constructor...."  << endl;
      }
      ~Derived2()
      {
      cout << "Derived2 Destructor..." << endl;
       }
    };
    
    
    
    int main()
    {
       cout << "Hello World" << endl; 
       Base1 b1; Base2 b2;
       Derived1 d1; 
       Derived2 d2;
       // Derived d; // - uncomment this line to get run-time error.
    
       return 0;
    }
    

提交回复
热议问题