How to randomly select a class to instantiate without using switch?

前端 未结 2 1059
既然无缘
既然无缘 2020-12-10 14:44

I\'m refactoring a single 3000+-line class with a tangled web of conditionals and switches into a set of worker classes. Previously part of the constructor would select whic

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 15:41

    The answer is : a base class and an array of function pointers can help you do that.

    struct Base { virtual ~Base() {} }; //make ~Base() virtual
    struct Foo : Base {};
    struct Bar : Base {};
    struct Baz : Base {};
    
    template
    Base *Create() { return new T(); }
    
    typedef Base* (*CreateFn)();
    
    CreateFn create[] = 
             {
                  &Create, 
                  &Create,   // weighted towards FOO
                  &Create, 
                  &Create
             }; 
    const size_t fncount = sizeof(create)/sizeof(*create);
    
    Base *Create()
    {
       return create[rand() % fncount](); //forward the call
    }
    

    Then use it as (ideone demo):

    int main() {
            Base *obj = Create();
            //work with obj using the common interface in Base
    
            delete obj; //ok, 
                        //the virtual ~Base() lets you do it 
                        //in a well-defined way
            return 0;
    }   
    

提交回复
热议问题