Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;使用共享的PTR实例化函数模板_C++_Templates_Polymorphism_Shared Ptr_Instantiation - Fatal编程技术网

C++ C++;使用共享的PTR实例化函数模板

C++ C++;使用共享的PTR实例化函数模板,c++,templates,polymorphism,shared-ptr,instantiation,C++,Templates,Polymorphism,Shared Ptr,Instantiation,可能重复: 当我们使用指针时,编译器在实例化方面没有问题 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;

可能重复:

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

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);
}
模板结构库{
虚拟~Base(){}
};
模板结构:公共基{
};
模板
空f(基*b){}
int main(){
derx;
f&x;
}
但是,如果我将f更改为使用共享的ptr,编译器将找不到匹配项

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> >&)’
模板
void f(shared_ptrb){}
int main(){
共享的ptr x(新的Der);
f(x);
}
Z.cc:在函数“int main()”中:
Z.cc:45:错误:对“f(std::tr1::shared_ptr&)”的调用没有匹配的函数
将x更改为

shared_ptr<Base<int> > x(new Der<int>);
shared_ptr x(新的Der);
也会起作用。 为什么会有这种行为上的差异?

shared\u ptr
不能隐式转换为
shared\u ptr
,而
Der*
可以隐式转换为
Base*
。因为模板参数类型是可转换的,所以C++不自动从模板转换的类型实例化,因为这不一定有意义,也可能是危险的。

有人能告诉我,为什么在重复问题的答案中,将Foo添加到call Foo中,会神奇地使事情正常进行?