使用weak_ptr作为参数重载分辨率的函数

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)

所以问题是:

  1. 编译错误: error C2440: 'static_cast' : cannot convert from 'B *const ' to 'A *'
  2. 编译错误: error C2668: ambiguous call to overloaded function

我不明白如何解决它们中的任何一个,因为:

  1. 我认为它以某种方式与shared_from_this连接,因为这是const指针.但我不知道如何在没有const_cast的情况下处理这种情况.
  2. 我不知道函数是否可以被不同类型的弱指针重载.

构建环境:MSVS 2013 express

请帮忙.谢谢

Rei*_*ica 6

至于问题(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).