gpt4 book ai didi

c++ - 以 weak_ptr 作为参数的函数重载决议

转载 作者:太空狗 更新时间:2023-10-29 20:03:47 25 4
gpt4 key购买 nike

我有:

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)
}

然后在B函数中:

void B::doReallyCoolStuff()
{
doCoolStuff(std::static_pointer_cast<B>(shared_from_this())); (2)
}

所以问题是:

  1. 编译器错误:错误 C2440:“static_cast”:无法从“B *const”转换为“A *”
  2. 编译器错误:错误 C2668:对重载函数的调用不明确

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

  1. 我认为它与 shared_from_this 有某种联系,因为这是常量指针。但是我不知道没有const_cast怎么处理这种情况。
  2. 我不知道函数是否可以被不同类型的弱指针重载。

构建环境:MSVS 2013 express

请帮忙。谢谢

最佳答案

至于问题(2),你当然可以这样重载。但问题是您正在调用类型为 std::shared_ptr<B> 的函数.这需要隐式转换为 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())));
}

Live example

或者,您可以提供 doCoolStuff 的重载服用std::shared_ptr .

如上面的实例所示,我无法重现问题 (1)。

关于c++ - 以 weak_ptr 作为参数的函数重载决议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25885164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com