static abstract methods in c++

前端 未结 3 2009
旧时难觅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:01

    There is no sure way to prescribe such a contract in C++, as there is also no way to use this kind of polymorphism, since the line

    Concrete::Factory()
    

    is always a static compile-time thing, that is, you cannot write this line where Concrete would be a yet unknown client-provided class.

    You can make clients implement this kind of "contract" by making it more convenient than not providing it. For example, you could use CRTP:

    class IThingy {...};
    
    template 
    class AThingy : public IThingy
    {
    public:
      AThingy() { &Derived::Factory; } // this will fail if there is no Derived::Factory
    };
    

    and tell the clients to derived from AThingy (you could enforce this with constructor visibility tweaking, but you cannot ensure the clients don't lie about their_class_name).

    Or you could use the classic solution, create a separate hierarchy of factory classes and ask the clients to provide their ConcreteFactory object to your API.

提交回复
热议问题