Class lookup structure array in C++

后端 未结 4 1495
花落未央
花落未央 2021-01-16 11:51

I\'m trying to create a structure array which links input strings to classes as follows:

struct {string command; CommandPath cPath;} cPathLookup[] = {
    {\         


        
4条回答
  •  滥情空心
    2021-01-16 12:34

    Personally I don't see it as being a huge problem if you just have 1 factory for creating different "CommandPaths" for different values of the string it receives. Anyway, your code won't work because you can't store types the way you're trying.

    If I had to do this, then for one I would use function pointers to factory functions and use a std::map to map strings to these, like shown in this code, and maybe wrap the pointers in an appropriate smart-pointer, instead of using raw pointers:

    #include 
    #include 
    
    struct A {
    };
    
    struct B : public A {
    };
    
    struct C : public A {
    };
    
    A *BFactory(){
        return new B();
    }
    
    A *CFactory(){
        return new C();
    }
    
    typedef A *(*Factory)();
    typedef std::pair Pair;
    typedef std::map Map;
    
    Pair Pairs[] = 
    {
        std::make_pair( "alarm", BFactory ),
        std::make_pair( "email", CFactory )
    };
    
    Map Lookup( Pairs, Pairs + sizeof(Pairs)/sizeof(*Pairs) );
    
    A *CreateInstance( const std::string &Type )
    {
        Map::const_iterator i = Lookup.find( Type );
    
        if( i != Lookup.end() )
            return i->second();
        else
            return 0;
    }
    

    As for your question about pointers and abstract classes, you can have a pointer to an abstract class, but you can't instantiate an abstract class.

提交回复
热议问题