Two things,
- don't use the
<U>
in the definition of CastTo<U>
,
- swap the order of
T
and U
in the template
line.
The first is just how the syntax for function templates goes in C++: no template brackets after their name. (But you will need one when calling the function.)
The second is more tricky. If you had a template<typename T, typename U>
function and called CastTo<DerivedClass*>(vec)
, then DerivedClass*
would be matched to the first parameter, T
, leaving no way of determining U
:
CastTo<DerivedClass*, ???>(vec): vector<DerivedClass*> &input -> ???
===== T ===== =U= ↑ T
> template argument deduction/substitution failed:
> couldn't deduce template parameter ‘U’
If it's template<typename U, typename T>
, then U
will be DerivedClass*
and T
can be found from the function's argument vec
:
1. CastTo<DerivedClass*, ???>(vec): vector<???> &input -> vector<DerivedClass*>
===== U ===== =T= ↑ vec ↑ U
2. vec is a vector<BaseClass*> => T = BaseClass*
> OK
This works (minimal example using primitive types and a C-style cast):
#include <vector>
using namespace std;
template<typename U, typename T>
vector<U> CastTo(vector<T> &input)
{
vector<U> output;
for (auto obj : input)
{
output.push_back(U(obj));
}
return output;
}
int main() {
vector<float> v{2,3,5};
vector<int> w = CastTo<int>(v);
return w[2]; // returns 5
}