开发者

how to replace string variable with its content?

开发者 https://www.devze.com 2023-02-15 21:49 出处:网络
I have a string variable var = \"BaseClass\", then i have to replace that var with its content in function e.g. i am calling \"BaseClass\" function like thisBaseClass::func_name();

I have a string variable var = "BaseClass", then i have to replace that var with its content in function e.g. i am calling "BaseClass" function like this BaseClass::func_name(); now my Question is that if i have to call function from the class whose name is st开发者_运维问答ored into var string i.e. var::func_name(), can we replace var variable with its content, and call correct class function.

Thanks in advance.


not sure this is what you're after, but you can keep a map with names as the key and pointers to BaseClass derived objects as value. Error checking omitted.

typedef std::map< std::string, BaseClass* > myMap;

class A : public BaseClass
{
  void func();
}

class B : public BaseClass
{
  void func();
}

myMap m;
A a;
B b;
m[ "A" ] = &a;
m[ "B" ] = &b;

std::string varName = GetVarNameFromSomeWhere();
m[ varName ]->func();


Simple Answer:

In C++, NO, you can't do this without using some 3rd party library or framework.


That's not possible in a generic way. The name of the class usually does not make it into the executable. Use function pointers (for static member functions) or member pointers (for non-static member functions) instead.


No, the compiler would not let that work since it wouldn't be able to do type inference after the interpolation of the variable is taken into account, it statically needs to be able to determine the type of class the method will be called with to generate the proper machine code.


You cannot define new types dynamically in C++ but you probably can in other languages (objective-C?). First of all, check if you really need that.

If you had a limited set of variable types you want to play with, i.e. Class1, Class2, ClassN, you could always do something like:

string var;
Class1 class1;
ClassN classN;
readFromSomewhere(var);
if (var == "Class1")
{
  class1.func_name();
}

Or it may be that what you really need is some type of inheritance and polymorphism code:

string var;
Base* p1 = new Class1();
Base* pN = new ClassN();
if (var == "Class1")
{
  p1->func_name();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号