Doc*_*sha 3 c++ smart-pointers static-cast weak-ptr c++11
我有:
class A : public std::enable_shared_from_this<A>
{...};
class B : public A
{...};
void doCoolStuff(std::weak_ptr<A> obj)
{...}
void doCoolStuff(std::weak_ptr<B> obj)
{
...
doCoolStuff(std::static_pointer_cast<A>(obj.lock())); (1)
}
Run Code Online (Sandbox Code Playgroud)
然后在B函数中:
void B::doReallyCoolStuff()
{
doCoolStuff(std::static_pointer_cast<B>(shared_from_this())); (2)
}
Run Code Online (Sandbox Code Playgroud)
所以问题是:
error C2440: 'static_cast' : cannot convert from 'B *const ' to 'A *'error C2668: ambiguous call to overloaded function我不明白如何解决它们中的任何一个,因为:
构建环境:MSVS 2013 express
请帮忙.谢谢
至于问题(2),你当然可以像这样超载.但问题是你用类型调用函数std::shared_ptr<B>.这需要隐式转换为a std::weak_ptr,它可以转换为std::weak_ptr<A>和std::weak_ptr<B>.这两个都是由内部的隐式转换构造函数实现的std::weak_ptr,这意味着它们都不比另一个好.因此含糊不清.
要解决此问题,您可以明确指定类型:
void B::doReallyCoolStuff()
{
doCoolStuff(std::weak_ptr<B>(std::static_pointer_cast<B>(shared_from_this())));
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以提供doCoolStuff服用的重载std::shared_ptr.
如上面的实例所示,我无法重现问题(1).