Monthly Archives: April 2020

避免function argument implicit conversion的方式

在std::string中,如果我們想要assign char 例如 std::string s = ‘A’; 這樣是不行的 必須要 std::string s(1, ‘A’); std::string的constructor 參考 http://www.cplusplus.com/reference/string/string/string/ 假想我們是string的設計者,加一個 string(char c); 會如何呢? 這樣看起來似乎完美方便,但其實在使用上多出了一些意想不到的情況 例如 std::string s = 123.4; 這樣就會走 string(char c);這條路而可以compile過,理由是Floating-integral conversions An rvalue of a floating point type can be converted to … Continue reading

Posted in C++ Language | Leave a comment

bool conversion test

後記:以下主要是展示template處理explicit bool operator的檢查所用的技巧,但其實真正要做cast檢查這樣檢查太瑣碎也不全面,可以透過std::is_constructible和std::is_convertible來處理,留待之後的文章整理 在C++中如果我們要知道物件轉成bool的值,可以直接用cast operator將型別轉成bool 例如 (bool)10.0 => true 但是像是 這段代碼顯然是無法通過編譯的(invalid cast from type ‘X’ to type ‘bool’),因為X沒有定義bool轉型的函式 假如我們想要設計一個function GetBool 可以檢查物件是否可轉成bool ─ 如果可以轉型就返回轉型的bool value, 如果不能轉型就返回false 因為使用的型別事先未知,所以勢必要使用template,根據使用者呼叫的參數來決定回傳值。因此很直覺的可以想到應該可以這樣做: 但是這樣做有個問題 ─ 那就是前面提到的,有些類別型別不支援bool轉型(沒有實作bool operator) ,必須在compile time要分兩個function,一個是可以轉型的,一個是不能轉型的,可是要讓呼叫者自己分辨傳入的參數顯然不太方便,這時候可以透過template metaprogramming的一些技巧讓compiler在compile time自動推導處理 這邊展示的GetBool作法參考了 gcc libstdc++-v3的is_convertible的概念實作 ─ 透過helper class推導”type” … Continue reading

Posted in C++ Language | Leave a comment