问题描述
|
假设我有两个不相关的类
A
和B
。我也有一个使用ѭ3uses的类Bla
:
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);
但是,如果在上述示例中从使用ѭ3切换为使用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;
}
顺便说一句,这个问题促使我问这个问题,我是否应该完全使用std::shared_ptr
;-)
解决方法
shared_ptr
具有模板单参数构造函数,此处将其视为转换对象。这就是在需要shared_ptr<Base>
的地方提供实际参数shared_ptr<Derived>
的原因。
由于shared_ptr<const A>
和shared_ptr<const B>
都具有这种隐式转换,因此它是模棱两可的。
至少在C ++ 0x中,该标准要求ѭ11使用一些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;
要求:除非constructor19ѭ可隐式转换为T*
,否则第二个构造函数不得参与重载解析。
可能尚未对库进行更新以符合该要求。您可以尝试更新版本的libc ++。
Boost无法使用,因为它缺少该要求。
这是一个更简单的测试用例:http://ideone.com/v4boA(该测试用例在合格的编译器上将失败,如果编译成功,则意味着原始用例将被错误地报告为模棱两可。)
VC ++ 2010正确(适用于std::shared_ptr
)。
, 以下代码可以在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);
}
, 您可以使用std::static_pointer_cast
添加const
资格:
bla.foo(std::static_pointer_cast<const A>(a));
, 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
{
}