Jump to content

Vector with template class as parameter

- - - - -

  • Please log in to reply
2 replies to this topic

#1
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
Hello,

I hope you can see what I'm trying to achieve because I can't come up with the words :)
#include <vector>

using namespace std;

class A {};
class B : public A {};

template <typename T>
class Response
{
private:
    T t;
};

int main()
{
    vector<Response<A> > names;

    Response<A> heman;
    names.push_back(heman);

    Response<B> hellman;
    names.push_back(hellman); // nogo!!
    return 0;
}

Everything works except the second push_back. The point is to have a container (e.g. vector)
which holds template objects. The template parameter is the superclass and the objects
are either of the superclass or its descendants.

Can it be done?

Edited by denarced, 03 November 2011 - 03:16 AM.


#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
To get polymorphic behavior, I believe you would need to use pointers to class A.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
To anyone interested in the answer, I've been reading on how the templates are processed.
When one writes different type parameters for template classes in code, the compiler merely
replaces the template T with the parameter and creates a new class. The different classes
aren't exactly related in any way and therefore what I tried to do is in fact impossible.

Am I wrong?




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users