Generalized copy constructors

Viewed 654

Why do classes like shared_ptr have another template in their constructors?

For example:

template<class T> class shared_ptr {
public:
  template<class Y>
  explicit shared_ptr(Y * p);

I've been reading Scott Meyers's Effective C++, item 45, which says the idea behind it is to make polymorphism possible through them; that is, construct shared_ptr<A> from shared_ptr<B> if B is derived from A.

But isn't defining a constructor like

explicit shared_ptr(T * p);

enough? I mean, this code works just fine:

class C1 {
};

class C2 : public C1 {
};

template<typename T>
class A
{
public:
  A(T &a)
  {
    var1 = a;
  }

  T var1;
};

int main(int argc, char *argv[])
{
  C2 c2;
  A<C1> inst1(c2);
}

So why do we need another template for constructor there?

2 Answers
Related