C ++ function template instance with shared_ptrs

Possible duplicate:
C ++ passing a derived shared_ptr class to a templated function

The compiler has no problem with creation when we use pointers.

template <typename T> struct Base{
  virtual ~Base() {}
};

template <typename T> struct Der: public Base<T> {
};


template <class T>
void f(Base<T>* b) {}

int main() {
  Der<int> x;
  f(&x);
}

      

However, if I change f to use shared_ptrs, the compiler cannot find a match.

template <class T>
void f(shared_ptr<Base<T> >b) {}

int main() {
  shared_ptr<Der<int> > x(new Der<int>);
  f(x);
}

Z.cc: In function ‘int main()’:
Z.cc:45: error: no matching function for call to ‘f(std::tr1::shared_ptr<Der<int> >&)
      

Change x to

shared_ptr<Base<int> > x(new Der<int>);

      

will also work. Why is there such a difference in behavior?

+3


source to share


1 answer


shared_ptr<Der<int>>

implicitly converts to shared_ptr<Base<int>>

, while Der<int>*

implicitly converts to Base<int>*

. C ++ does not allow automatic creation of types created from a convertible template, just because the types of the template parameters turn out to be convertible, because this does not necessarily make sense and can be dangerous.



http://www2.research.att.com/~bs/bs_faq2.html#conversion

0


source







All Articles