假设我有两个不相关的AB。我也有一个使用Blaboost::shared_ptr类,如下所示:

class Bla {
public:
    void foo(boost::shared_ptr<const A>);
    void foo(boost::shared_ptr<const B>);
}

注意 const 。那是这个问题的原始版本所缺少的重要部分。这将编译,并且以下代码有效:
Bla bla;
boost::shared_ptr<A> a;
bla.foo(a);

但是,如果在上述示例中从使用boost::shared_ptr切换为使用std::shared_ptr,则会出现编译错误,内容为:
"error: call of overloaded 'foo(std::shared_ptr<A>)' is ambiguous
note: candidates are: void foo(std::shared_ptr<const A>)
                      void foo(std::shared_ptr<const B>)

您能帮我弄清楚为什么编译器为什么不能在std::shared_ptr情况下弄清楚使用哪个函数,而在boost::shared_ptr情况下却不能解决?我正在使用Ubuntu 11.04软件包存储库中的默认GCC和Boost版本,当前是GCC 4.5.2和Boost 1.42.0。

这是您可以尝试编译的完整代码:
#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
// #include <memory>
// using std::shared_ptr;

class A {};
class B {};

class Bla {
public:
    void foo(shared_ptr<const A>) {}
    void foo(shared_ptr<const B>) {}
};

int main() {
    Bla bla;
    shared_ptr<A> a;

    bla.foo(a);

    return 0;
}

顺便说一句,这个问题促使我向this question询问我是否应该完全使用std::shared_ptr ;-)

最佳答案

shared_ptr具有模板单参数构造函数,在此将其视为转换对象。这就是在需要shared_ptr<Derived>的地方提供实际参数shared_ptr<Base>的原因。

由于shared_ptr<const A>shared_ptr<const B>都具有这种隐式转换,因此它是模棱两可的。

至少在C++ 0x中,该标准要求shared_ptr使用一些SFINAE技巧来确保模板构造函数仅匹配实际可以转换的类型。

签名是(请参阅[util.smartptr.shared.const]部分):

shared_ptr<T>::shared_ptr(const shared_ptr<T>& r) noexcept;
template<class Y> shared_ptr<T>::shared_ptr(const shared_ptr<Y>& r) noexcept;



可能尚未对该库进行更新以符合该要求。您可以尝试更新版本的libc++。

Boost无法使用,因为它缺少该要求。

这是一个更简单的测试用例:http://ideone.com/v4boA(该测试用例在合格的编译器上将失败,如果编译成功,则意味着原始用例将被错误地报告为模棱两可。)

VC++ 2010正确(针对std::shared_ptr)。

07-24 09:46
查看更多