簡體   English   中英

函數重載bool和boost :: shared_ptr之間的ambiguty <base> 用boost :: shared_ptr調用時 <derived>

[英]function overloading ambiguty between bool and boost::shared_ptr<base> when calling with boost::shared_ptr<derived>

#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:在函數'int main()'中:shared_test.cpp:27:13:錯誤:調用重載'g(boost :: shared_ptr& )'是模糊的shared_test.cpp:27:13:注意:候選人是:shared_test.cpp:7:6:注意:void g(bool)shared_test.cpp:9:6:注意: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 ,因為在這兩種情況下都會調用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

它不是復制構造函數,它是轉換構造函數,所以鏈就像這樣

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

只有一種方法可以做你想要的:構造類型為shared_ptr<base>臨時表。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM