混沌 IN C++::轉換函式

來源:互聯網
上載者:User

難度:

問題:

    下面這段代碼為什麼會編譯失敗呢?

 

struct T

{

    operator
std::string() const

    {

       return
std::string();

    }

   

    operator
int() const

    {

       return
int();

    }

};

 

int  
main()

{

    T t;

    int
i = t;

    std::string s = t;

   

    i == t;    //成功

    s == t;    //失敗

}

 

回答:

    因為標準庫沒有提供bool operator==(const
std::string&, const std::string&);這樣的重載,而是提供了

    template<typename CharT, typename
Traits, typename Alloc>

    bool
operator==(const std::basic_string<CharT, Traits, Alloc>&, const std::basic_string<CharT,
Traits, Alloc>&);

 

    當s == t 進行比較的時候,編譯器用第一個參數s可以推匯出CharT, Traits, Alloc這三個模板參數,然後用t來推導,結果是無法完成推導,因為t並不是basic_string<>。那T中的operator std::string() const的轉換函式在這裡有什麼作用呢?事實上,這個轉換函式在這裡一點用也沒有,C++沒有提供一個規則是先轉換再推導函數模板參數的。解決這個問題的辦法,就是讓編譯器在推導第二個參數的類型之前,顯式地將t轉換為std::string。

s == std::string(t);

   

    到這一步,有人又會納悶,basic_string也沒提供basic_string(const
std::string&)的建構函式啊,而是提供的

    template<typename CharT, typename
Traits, typename Alloc>

    basic_string(const basic_string<CharT, Traits, Alloc>&);

    按照上面的說法,那顯式轉換std::string(t)是怎麼完成推導函數模板參數的呢? 其實std::string並不是類模板了,而是被執行個體化成basic_string<char>這個模板類,std::string(t)也沒有進行推導,因為已經明確了CharT, Traits,
Alloc這三個模板參數,所以這時的operator std::string() const起作用了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.