用shared_ptrs实现函数模板的C++实例化

C++ instantiation of function template with shared_ptrs

本文关键字:C++ 实例化 函数模板 实现 shared ptrs      更新时间:2023-10-16

可能重复:
C++将派生类shared_ptr传递给模板化函数

当我们使用指针时,编译器在实例化方面没有问题。

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);
}

但是,如果我将f更改为使用shared_ptrs,编译器将找不到匹配项。

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> >&)’

将x更改为

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

也会起作用。为什么行为上会有这种差异?

shared_ptr<Der<int>>不可隐式转换为shared_ptr<Base<int>>,而Der<int>*可隐式转化为Base<int>*。C++不会因为模板参数类型恰好是可转换的,就自动使从模板实例化的类型可转换,因为这不一定有意义,而且可能很危险。

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