template<class T>
T str2Type(string str) // assume str will only be "int", "string" or "double"
{
if("int" == str)
{
return 1;
}
elseif("string" == str)
{
return"hello";
}
else
{
return 5.6;
};
};
int main()
{
string str;
getline(cin, str);
cout << str2Type(str) << endl;
return 0;
};
The idea is that I want to take user input into string variable str, and depending on the user's command, I'd like to return something of the proper type.
Assume that user only inputs a string to show what type of variable he wants.
The compiler complains:
error: no matching function for call to ‘str2Type(std::string&)’
which kinda makes sense to me because the compiler must be looking for some function with the stated signature and couldn't find one. The template is indeed defined, but there's no hint in main() instructing the compiler to generate code from the template.
On the other hand, what I'm trying to do is self-evident: I'm trying to generate a variable at run time, whose type is NOT known until run time.
Types are fixed at compile time so it's not possible to do what you are trying to do.
What you could do is to create some wrapper class that can somehow behave like one of int/double/string but I doubt that is the best way.
Templates need to be known what type they are at compile time, that's the way they work. The error your getting is because there is nothing defining what to use for T, since there are no templated parameters and the return type has no say to what type it is.
You can just do what you have there just remove the function and write code for each case.
The real issue here is that the return type of funtions is not part of a function's signature. Even if you were to to int x (str2Type("1")); it would not work, because the return type is only used for maintining a strongly typed language. Other than that enforcement, the return type is ignored and irrelevant to any of the more advanced features of C++ such as function overloading and templates.