【发布时间】:2012-03-19 18:54:21
【问题描述】:
可能重复:
C++ passing a derived class shared_ptr to a templated function
当我们使用指针时,编译器在实例化方面没有问题。
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>);
也可以。 为什么会有这种行为差异?
【问题讨论】:
-
有人能告诉我为什么在重复问题的答案中将 Foo 添加到调用 foo
会神奇地使事情正常进行吗?
标签: c++ templates polymorphism shared-ptr instantiation