C++ 0x错误:使用std :: shared_ptr将函数重载到const参数是不明确的

Ala*_*ing 6 c++ boost stl overloading shared-ptr

假设我有两个不相关的AB.我也有一个Bla使用boost::shared_ptr这样的类:

class Bla {
public:
    void foo(boost::shared_ptr<const A>);
    void foo(boost::shared_ptr<const B>);
}
Run Code Online (Sandbox Code Playgroud)

请注意const.这是这个问题的原始版本所缺乏的重要部分.这个编译,以下代码工作:

Bla bla;
boost::shared_ptr<A> a;
bla.foo(a);
Run Code Online (Sandbox Code Playgroud)

但是,如果我在上面的例子中从使用切换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>)
Run Code Online (Sandbox Code Playgroud)

你能帮我弄清楚为什么编译器无法弄清楚在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;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这个问题促使我问这个问题我是否应该使用std::shared_ptr;-)

Ben*_*igt 7

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;
Run Code Online (Sandbox Code Playgroud)

要求:第二个构造函数不应参与重载决策,除非Y*可以隐式转换为T*.

可能图书馆尚未更新以符合该要求.您可以尝试更新版本的libc ++.

Boost不起作用,因为它缺少这个要求.

这是一个更简单的测试用例:http://ideone.com/v4boA (此测试用例将在符合标准的编译器上失败,如果编译成功,则表示原始案例将被错误地报告为不明确.)

VC++ 2010做得对(for std::shared_ptr).


Mot*_*tti 6

以下编译与GCC 4.5和Visual Studio 10编译良好.如果你说它不能在GCC 4.5.2中编译,那么它听起来像你应该报告的编译器错误(但要确保它真的发生它更可能是你做的某种错字).

#include <memory>
class A{};
class B{};
class Bla {
public:
    void foo(std::shared_ptr<A>) {}
    void foo(std::shared_ptr<B>) {}
};

int main()
{
    Bla bla;
    std::shared_ptr<A> a;
    bla.foo(a);
}
Run Code Online (Sandbox Code Playgroud)