gpt4 book ai didi

c++ - 使用 boost::shared_ptr 调用时 bool 和 boost::shared_ptr 之间的函数重载歧义

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

#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

struct base {};
struct derived : public base {};

void g(bool b) {}

void g(boost::shared_ptr<base> b) {}

int main()
{
boost::shared_ptr<base> spbase = boost::make_shared<derived>();
boost::shared_ptr<derived> spderived = boost::make_shared<derived>();

g(true); // ok
g(spbase); //ok
g(boost::static_pointer_cast<base>(spderived)); // ok
g(spderived); // I am ambiguous between g(bool b) and g(boost::shared_ptr<base> b).
}

有人可以向我解释为什么对 g(spderived) 的调用导致 g(bool) 和 g(boost::shared_ptr) 之间的歧义吗?

使用 gcc 版本 4.6.3 编译会出现以下错误:

$ g++ shared_test.cpp -I/c/thirdparty/boost_1_55_0/ -o shared_test shared_test.cpp: In function 'int main()': shared_test.cpp:27:13: error: call of overloaded 'g(boost::shared_ptr&)' is ambiguous shared_test.cpp:27:13: note: candidates are: shared_test.cpp:7:6: note: void g(bool) shared_test.cpp:9:6: note: void g(boost::shared_ptr)

注意:如果我添加 -std=c++11,它编译得很好,但我使用的是 c++98/c++03,所以这对我没有多大帮助。Clang 和 VC 产生类似的错误,在 c++03 下编译。

最佳答案

在 C++03 中 shared_ptr具有隐式 bool 转换运算符,在 C++11 中它是显式的。这个调用是模棱两可的,因为在这两种情况下都是 user-defined conversion会被调用,转换为bool,或者转换为shared_ptr<base> , 定义如下:

template<class Y>
#if !defined( BOOST_SP_NO_SP_CONVERTIBLE )

shared_ptr( shared_ptr<Y> const & r,
typename boost::detail::sp_enable_if_convertible<Y,T>::type =
boost::detail::sp_empty() )

#else

shared_ptr( shared_ptr<Y> const & r )

#endif

不是拷贝构造函数,是转换构造函数,所以chain会是这样

tmp = shared_ptr<base>(spderived);
b = shared_ptr<base>(tmp);

只有一种方法可以做你想做的事:构造临时类型 shared_ptr<base> .

g(boost::shared_ptr<base>(spderived));

关于c++ - 使用 boost::shared_ptr<derived> 调用时 bool 和 boost::shared_ptr<base> 之间的函数重载歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356491/

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