質問

I've got some difficult (for me) problem with functions in C++. I've made some classes, like Numbers, Characters and so. Each class has a void add function, but Numbers have void add(int v), Characters - void add(char c), etc. In the main function, I've got Numbers and other classes' instances (numbs, charcts) and I would like to bind those with std::map, so I will be able to call functions like that:

func_map["numbers"]["add"](12);

which will be the same as:

numbs.add(12);

But it'll be easier for me, if I could call methods by giving just their names as strings (like show above). How should I do that?

役に立ちましたか?

解決

I would warn you against such a design.

But, well, if you absolutely need that, you have to define a common interface to your functions. That is, your functions must have the same prototype.

For example, you can define some container class (or use something like boost::variant) that can be constructed from different data types, and you can write your 'add' functions so they accept an object of this class. What I mean is:

class DataContainer { 
 public:
  DataContainer(int n) { int_data_ = n; }
  DataContainer(char c) { int_data_ = c; }
  DataContainer(const string s) { string_data_ = s; }
 // let them be public to make code shorter
  int int_data_;
  string string_data_;
};

typedef void (*OpMethod)(const DataContainer);

void NumberAdd(const DataContainer data) {
  // work with data.int_data_
}

map<string, map<string, OpMethod> > funcmap; 

...
  funcmap["number"]["add"] = NumberAdd;

Binding class methods would be a bit more difficult (you should specify an object instance as well). Consider using std::function.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top