static abstract methods in c++

前端 未结 3 1994
旧时难觅i
旧时难觅i 2020-12-06 04:20

I have an abstract base class

class IThingy
{
  virtual void method1() = 0;
  virtual void method2() = 0;
};

I want to say - \"all classes

3条回答
  •  有刺的猬
    2020-12-06 05:06

    The problem that you are having is partly to do with a slight violation a single responsibility principle. You were trying to enforce the object creation through the interface. The interface should instead be more pure and only contain methods that are integral to what the interface is supposed to do.

    Instead, you can take the creation out of the interface (the desired virtual static method) and put it into a factory class.

    Here is a simple factory implementation that forces a factory method on a derived class.

    template 
    class Factory {
    public:
        static TInterface* Create(){return TClass::CreateInternal();}
    };
    
    struct IThingy {
        virtual void Method1() = 0;
    };
    
    class Thingy : 
        public Factory,
        public IThingy {
            //Note the private constructor, forces creation through a factory method
            Thingy(){}
    public:
            virtual void Method1(){}
            //Actual factory method that performs work.
            static Thingy* CreateInternal() {return new Thingy();}
    };
    

    Usage:

    //Thingy thingy; //error C2248: 'Thingy::Thingy' : cannot access private member declared in class 'Thingy'
    
    IThingy* ithingy = Thingy::Create(); //OK
    

    By derinving from Factory, the derived class is forced to have a CreateInternal method by the compiler. Not deifining it will result in an error like this:

    error C2039: 'CreateInternal' : is not a member of 'Thingy'

提交回复
热议问题