How to treat Base* pointer as Derived<T>* pointer?

Posted by dehmann on Stack Overflow See other posts from Stack Overflow or by dehmann
Published on 2010-04-17T22:18:41Z Indexed on 2010/04/17 22:23 UTC
Read the original article Hit count: 242

Filed under:
|
|

I would like to store pointers to a Base class in a vector, but then use them as function arguments where they act as a specific class, see here:

#include <iostream>
#include <vector>

class Base {};

template<class T>
class Derived : public Base {};

void Foo(Derived<int>* d) {
  std::cerr << "Processing int" << std::endl;
}

void Foo(Derived<double>* d) {
  std::cerr << "Processing double" << std::endl;
}

int main() {
  std::vector<Base*> vec;
  vec.push_back(new Derived<int>());
  vec.push_back(new Derived<double>());
  Foo(vec[0]);
  Foo(vec[1]);
  delete vec[0];
  delete vec[1];
  return 0;
}

This doesn't compile:

error: call of overloaded 'Foo(Base*&)' is ambiguous

Is it possible to make it work? I need to process the elements of the vector differently, according to their int, double, etc. types.

© Stack Overflow or respective owner

Related posts about c++

Related posts about templates