跳到主要內容

發表文章

目前顯示的是 5月, 2019的文章

C++17 新功能 - string_view

C++17 新功能 - string_view string_view 使用 std::string 來做字串解析的好處是可以利用其各式各樣的功能,像是 substr 、 find 等,缺點則是 std::string 實作設計成 value semantic,複製與賦值都隱含 heap 操作 ,即使是 C++11 有了 move semantic 得以避免複製,還是得付出解構的成本。為了解決這個問題,C++14 加入了 std::experimental::string_view ,這個類別可以基於 char const * 或是 std::string 建構,提供唯讀的參照到原本的記憶體。舉例如下 # include <experimental/string_view> # include <assert> using namespace std ; using namespace std :: experimental ; int main ( ) { char const * data = "asdf" ; string_view sv ( data ) ; assert ( data == sv . data ( ) ) ; // 記憶體位置相同 sv [ 0 ] = 'b' ; // compiler error (string_view 是唯讀) } 因為是唯讀參照,不需要任何 heap 上的操作,可以節省相當的成本。類似功能在 C++14 之前,許多函式庫就已經提供類似的功能,例如 re2::StringPiece 、boost::string_ref、llvm::stringref 等。這次在 C++17 看來沒太多爭議就納入標準函式庫成為 std::string_view 。 實例運用 使用 std::string 實作的簡易字串分割 輸入:“a,b,c,d” 輸出: a b c d # include <string> using namespace std ; struct tokenizer {

C++ 不用 typeid 印出型別名稱

C++ 不用 typeid 印出型別名稱 方便檢驗型別的小技巧 編譯期印出 template < typename T > void print_type ( ) ; int main ( ) { print_type < int > ( ) ; return 0 ; } 輸出 undefined reference to `void print_type<int>()' 執行期印出 template < typename T > void print_type ( ) { cout << __PRETTY_FUNCTION__ << endl ; // GCC & clang extension } 輸出 void print_type() [with T = int] MSVC 的話用 __FUNCSIG__ 取代 __PRETTY_FUNCTION__ 。 Written with StackEdit .