Reputation: 18218
I want to write a function such as this:
template<class T1, T2>
T2 getvalue(T1 in)
{
T2 tmp;
// do some work here
return T2;
}
and call in this way:
float x[100];
int x=getvalue<int>(x);
But it seems that I can not do this. The idea is that compiler detect the T1 from usage but I define the return type. But the above code generate an error.
Any suggestion on how I can do this?
Upvotes: 1
Views: 166
Reputation: 159
good question, templates can get tricky in C++.
correctly written version:
template<typename T1, typename T2>
T2 getvalue(T1 in)
{
T2 tmp;
// do some work here with tmp
return tmp;
}
Correct way to calling per your example:
float x[100]; //array of 100 floats. depending on your application, best practice would suggest to initial the values in the array to 0.
int x=getvalue<double, int>(3.5); //note int x is different than float x[].
Your function is currently returning an int. if you want to return an array of floating point number, your template argument should reflect that as well. best to always specify both template parameters. remember function templates cannot be partially specialized unlike class templates(only fully)
just my $0.02
Upvotes: 0
Reputation: 101494
First off, you have a typo. In your return
statement, you're attempting to return a type, not a name. Change:
return T2;
to:
return tmp;
Second, you have a further syntax error in your template parameter list. You need either class
or typename
to precede each and every template parameter name (I prefer typename
, but that's me):
template<typename T1, typename T2>
Finally, you can get deduction to work as you wish by making the return type the first template parameter:
template<typename T1, typename T2>
T1 getvalue(T2 in)
{
T1 tmp;
// do some work here
return tmp;
}
Decuction will now work as you expect:
bool b = getValue <bool> (42.0);
The reason for this is template parameters are evaluated from left to right, not in arbitrary order. The compiler will attempt to deduce any template parameters not specified once the left-most ones have been applied.
Upvotes: 2
Reputation: 477504
When you specify function template arguments explicitly, they're filled in from the left; all remaining arguments are deduced. So you have to write it like this:
template <typename T, typename U>
T getvalue(U in)
{
return in;
}
Usage:
auto x = getvalue<int>(1.5); // x is an "int", and U is deduced as "double"
Upvotes: 5