In C++, is there a nice technique or design pattern to perform the following tasks based on configuration?
Scenario #1: Call开发者_开发技巧 functions
If a configuration says:A:foo()
Then the code should call A::foo() assuming that the object of A is already accessible.
Scenario #2: Declare type
If a configuration says:
bar:vector<std::string>
Then the code should create an object with the type vector<std::string>
in runtime.
String match solution is not desirable.
Thanks in advance.
You can do this but it requires a lot of preparation and prior knowledge. Basically you'd need to create function pointers to all your class methods, those methods would have to have the same signature, and you'd need to hold all of this information in a hashtable. Like this:
class Foo {
public:
void MyMethod1(int _input);
void MyMethod2(int _input);
.
.
.
void MyMethodN(int _input);
};
typedef (Foo::*foo_func)(int);
class Acceptor{
public:
void Command(Foo &_foo, string _name, int _arg){
return _foo.*(m_MappedFunctions[ _name ])(_arg);
}
private:
unordered_map<String,foo_func> m_MappedFunctions;
};
where you've placed function pointers to all of Foo
's methods in the hashtable. You see? It's both inflexible and requires a lot of coordinate between code, configuration file and calling convention.
There is no portable way to do something like this. C++ does not have runtime reflection capabilities which is what your solution would require.
Unless you want to do something non-portable (read the debug symbols to find your symbols, and even then that won't work if you have a build without debug symbols), you are going to need to do some sort of "string match" solution and that will limit you to only being able to support the types you added to your string table during development.
精彩评论