假设我有两个无关的类A
和B
。我还有一个使用Bla
的课程boost::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
; - )
答案 0 :(得分: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;
要求:第二个构造函数不应参与重载决策,除非
Y*
可隐式转换为T*
。
图书馆可能尚未更新以符合该要求。您可以尝试更新版本的libc ++。
Boost不起作用,因为它缺少这个要求。
这是一个更简单的测试用例:http://ideone.com/v4boA(此测试用例将在符合标准的编译器上失败,如果编译成功,则表示原始案例将被错误地报告为不明确。)
VC ++ 2010使它正确(对于std::shared_ptr
)。
答案 1 :(得分: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);
}
答案 2 :(得分:2)
您可以使用std::static_pointer_cast
添加const
资格:
bla.foo(std::static_pointer_cast<const A>(a));
答案 3 :(得分:0)
http://bytes.com/topic/c/answers/832994-shared_ptr-derived-classes-ambiguitity-overloaded-functions
struct yes_type { char dummy; };
struct no_type { yes_type a; yes_type b; };
template < typename From, typename To >
class is_convertible
{
private:
static From* dummy ( void );
static yes_type check ( To );
static no_type check ( ... );
public:
static bool const value = sizeof( check( *dummy() ) ) == sizeof( yes_type );
}; // is_convertible
在boost的shared_ptr.h中,将构造函数签名更改为:
template<class Y>
shared_ptr(shared_ptr<Y> const & r,
typename enable_if<is_convertible<Y*, T*>::value, void*>::type = 0
): px(r.px), pn(r.pn) // never throws
{
}