Class lookup structure array in C++

后端 未结 4 1492
花落未央
花落未央 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:50

    You can't store a type in a struct, but you can store a pointer to a function that creates a type.

    CommandPath * CreateEmail() {
         return new EmailCommandPath;
    }
    
    CommandPath * CreateAlarm() {
         return new AlarmCommandPath;
    }
    

    Then your struct looks like:

    typedef Command * (* CreateFunc)();
    struct MyMap {
       string command;
       CreateFunc func;
    };
    

    and the map:

    MyMap m[] = {{"email", CreateEmail }, {"alarm", CreateAlarm}};
    

    You then look up as before to get some index i, and use it:

    CommandPath * p = m[i].func():
    

    And you can create pointers to abstract types - you can't create instances of them.

提交回复
热议问题