-1

I want to cast BaseClass to DerivedClass std vector using a template:

template<typename T, typename U>
vector<U> CastTo<U>(vector<T> &input)
{
    vector<U> output;
    for (auto obj : input)
    {
        output.push_back(dynamic_cast<U>(obj));
    }
    return output;
}

Is this possible?

Right now the template is not being recognized and I not able to use it. Is there a mistake in the proposed way?

The usage is:

vector<BaseClass*> vec;
vector<DerivedClass*> dVec = CastTo<DerivedClass*>(vec);
Sturm
  • 3,968
  • 10
  • 48
  • 78

2 Answers2

4
template<typename T, typename U>
vector<U> CastTo<U>(vector<T> &input)
                ^^^

Remove that <U> (why the ALL_UPPERCASE that's for macros?). Also, be aware that your example call might be confusing T and U.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
3

Two things,

  1. don't use the <U> in the definition of CastTo<U>,
  2. 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
}
The Vee
  • 11,420
  • 5
  • 27
  • 60