【问题标题】:C++ instantiation of function template with shared_ptrs [duplicate]具有shared_ptrs的函数模板的C ++实例化[重复]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-11
    • 2010-09-18
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    相关资源
    最近更新 更多