Reputation: 47
Basically, if I have this:
template <class T>
inline T Foo(int x)
{
switch (x)
{
case 0:
return true;
break;
case 1:
return false;
break;
case 2:
return 100;
break;
default:
break;
}
}
I then have to use it as such:
int x = Foo<int>(2);
bool b = Foo<bool>(0);
I would much prefer to be able to do it like this, if possible:
int x = Foo(2);
bool b = Foo(0);
I saw this question but struggled to apply it to my scenario. Any help or pointing in the right direction would be great.
Upvotes: 1
Views: 430
Reputation: 59
The idea here is to use a return type which is convertible to our desired return types. In this case, we can use string which can be converted to int, bool, double etc.. using stringstream.
inline polyType Foo(int x)
{
polyType result;
switch (x)
{
case 0:
result.value = "0";
break;
case 1:
result.value = "1";
break;
case 2:
result.value = "100";
break;
case 3:
result.value = "awesome";
break;
case 4:
result.value = "10.22";
break;
default:
break;
}
return result;
}
where polyType is to declared as the following with a type cast for any typename T as described here
struct polyType {
string value;
template <typename T>
operator T() const
{
stringstream ss(value);
T convertedValue;
if ( ss >> convertedValue ) return convertedValue;
else throw runtime_error("conversion failed");
}
};
Now you can use it as
int a = Foo(2);
bool b = Foo(0);
float c = Foo(4);
In your case if you want to use only int and bool. since int is convertible to bool you can just return int. Instead of returning "true" and "false" use 1 and 0.
int Foo(int x)
{
switch (x)
{
case 0:
return 1;
break;
case 1:
return 0;
break;
case 2:
return 100;
break;
default:
break;
}
}
Upvotes: 1
Reputation: 976
AFAIK the compiler can't implicitly determine template parameters based on return type alone. It can usually determine them implicitly if you pass them in as parameters (function templates).
So, one thing that might work better is passing the template parameters in by reference:
template <typename T>
void Foo(int x, T& arg1)
{
if (x == 0)
arg1 = true;
else if (x == 1)
arg1 = "test";
}
bool a = false;
std::string b;
Foo(0, a);
Foo(1, b);
Upvotes: 0