从int到shared_ptr的隐式转换 [英] Implicit conversion from int to shared_ptr
本文介绍了从int到shared_ptr的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码:
#include< iostream&
#include< memory>
void f(std :: shared_ptr< int> sp){}
template< typename FuncType,typename PtrType>
auto call_f(FuncType f,PtrType p) - > decltype(f(p))
{
return f(p);
}
int main()
{
f(0); //不为任何其他int!= 0工作,感谢@Rupesh
// call_f(f,0); //错误,无法将int转换为shared_ptr
}
c $ c> main(),则将整数 0
转换为 std :: shared_ptr< int& code>并且调用
f(0)
成功没有任何问题。但是,使用模板调用函数使事物不同。第二行将不再编译,错误是
错误:无法将'p'从'int'转换为'std: :shared_ptr< int>'
我的问题是:
$ b b
- 为什么第一次调用成功,第二次调用不成功?
- 我不明白如何从
int
到f(0)
,因为它看起来像std :: shared_ptr,正在执行> std :: shared_ptr
PS:此示例的一个变体出现在Scott Meyers的 Effective Modern C ++
解决方案