Reputation: 61
I am extracting a string from a .txt
file and saving it in a variable:
std::string line = "The king's name is getKingName()";
Lets assume that getKingName()
is a function that returns a King
class' name
data member.
How can I make a call to getKingName()
when the string variable looks like that?
Upvotes: 0
Views: 156
Reputation: 137
As far as I know, C++ does not provide such kind of functionality to interpolate functions call inside a string. All you can do implement your own logic to do that. Like,
1) define all the valid methods like this,
string getKingName(){
return "Some name";
}
string otherMethods(){
return "other values";
}
2) One helper method for mapping of function call
string whomToCall(string methodName){
switch(methodName){
case "getKingName()":
return getKingName();
break;
case "otherMethods()":
return otherMethods();
break;
default:
return "No such method exist";
}
}
3) break the line in tokens(words), read one by one and check for following condition also if
token starts with any alphabetical character and ends with "()" substring
istringstream ss(line);
do {
string token;
ss >> token;
if(isMethod(token))
cout << whomToCall(token) << " ";
else
cout << token<< " ";
} while (ss);
4) isMethod() to check if token's value can be a valid method name
bool isMethod(string token){
int n= token.length();
return isalpha(token[0]) && token[n-2]=='(' && token[n-1] == ')' ;
}
Upvotes: 2
Reputation: 1091
This is not supported by C++. C++ is not an interpreted language. If you you want to do things like this, why not use an interpreted language, which do these sorts of things by default. Languages like lua are designed to call C/C++ functions with an interpreted language, with a small overhead.
However, if you really need to do this, it is possible, depending on your operating system. For example,
That said, there are lots of gotchas doing it this way. Optimization can get in the way (best to disable them). Also best to avoid dynamic linking (prefer static). You will also need to cope with C++ name mangling (the name of the function is not the name of your function in C++). see https://blog.oakbits.com/how-to-mangle-and-demangle-a-c-method-name.html.
Upvotes: 0
Reputation: 3001
This would be the easiest solution, but I think your problem consists of several such calls?
std::string line = "The king's name is getKingName()";
if (line.find("getKingName()") != std::string::npos) {
King name = getKingName();
}
Upvotes: 1