跳到主要內容

發表文章

Devirtualization and TDD

Devirtualization and TDD Devirtualization (去虛擬化) Devirtualization 是 C++ 編譯器的一種最佳化,舉個例子: struct foo { virtual ~ foo ( ) { } virtual int bar ( ) = 0 ; } ; struct food : foo { int bar ( ) final { return 2 ; } } ; struct fool : foo { int bar ( ) override { return 3 ; } } ; int test ( food & f ) { return f . bar ( ) ; } int test ( fool & f ) { return f . bar ( ) ; } test(food& f) 用 -O2 編譯後產生的組語是 test(food&): mov eax, 2 ret 而 test(fool& f) 則產生 test(fool&): mov rax, QWORD PTR [rdi] mov rax, QWORD PTR [rax+16] cmp rax, OFFSET FLAT:fool::bar() jne .L6 mov eax, 3 ret .L6: jmp rax 差別在於前者用了 final 而後者使用 override , final 可以告訴編譯器 food::bar 不會再被衍生型別覆寫,因此不需要查找 vtable 而直接呼叫 food::bar 。 final 也可以用來敘明類別不會被其他類別繼承。例如: struct foot final : foo { /* impl */ } ; 以上可以發現,能套用 devirtualization 的...

std::optional 的未來?

std::optional<T&> 的未來? 前言 春節就是拋拋走,趁著搭車的時間看完 JeanHeyd Meneide (ThePhantomDerpstorm/ThePhD) 的 血淚控訴 To Bind and Loose a Reference 1 ,他聲稱:標準委員會因為一個不存在的對手,訂定了一個殘缺的 std::optional 。文章非常值得一讀,寫不出配得上的心得,只好寫一篇筆記。 Nullable 型別 C++17 增添了 std::optional<T> ,C++20 加入了 std::variant<Ts...> ,C++2x 預計會出現 std::expected<T> ,這些工具的相同點在於他們都是 nullable 型別 ─ 物件狀態可以是含有 T 或者不含有 T (也就是 null),雖然應用在不同的情境上,但某種程度上都可以理解為特化版的指標。 Reference 有甚麼問題? std::optional 在 cppreference.com 裡的描述 2 裡面有一句話: There are no optional references; a program is ill-formed if it instantiates an optional with a reference type. 同樣適用於 std::variant 、 std::expected 。其實在 Boost.Optional 或是 Boost.Variant 都是支援 reference 型別的,然而 C++ 標準委員會對下面這段程式分裂成兩派不同的見解 (範例取自 JeanHeyd Meneide): # include <optional> # include <iostream> int main ( int , char * [ ] ) { int x = 5 ; int y = 24 ; std :: optional < int & > opt = x ; opt = y ; std :: cout <...

C++17 新功能 try_emplace

C++17 新功能 try_emplace 回顧 emplace 大家的好朋友 Standard Template Library (STL) 容器提供如 push_back , insert 等介面,讓我們塞東西進去; C++11 之後,新增了 emplace 系列的介面,如 std::vector::emplace_back , std::map::emplace 等,差異在於 emplace 是在容器內 in-place 直接建構新元素,而不像 push_back 在傳遞參數前建構,下面用實例來說明: struct Value { // ctor1 Value ( int size ) : array ( new char [ size ] ) , size ( size ) { printf ( "ctor1: %d\n" , size ) ; } // ctor2 Value ( const Value & v ) : array ( new char [ v . size ] ) , size ( v . size ) { printf ( "ctor2: %d\n" , size ) ; memcpy ( array . get ( ) , v . array . get ( ) , size ) ; } private : std :: unique_ptr < char [ ] > array ; int size = 0 ; } ; struct Value 定義了自訂建構子 (ctor1),以指定大小 size 配置陣列,複製建構子 (ctor2) 則會配置與來源相同大小及內容的陣列,為了方便觀察加了一些 printf 。當我們如下使用 std::vector::push_back 時 std :: vector < Value > v ; v . push_back ( Value ( 2048 ) ) ; 首先 Value 會先呼叫 ctor1,傳給 push_ba...

KNN Text Classification

KNN Text Classification Simplified Data Set Assume terms a document are unique (tag-like dataset). doc terms d0 [ t0, t2, t3 ] d1 [ t1, t3 ] d2 [ t0, t2 ] and docs = [ d0, d1, d2 ] d0.terms = [ t0, t2, t3 ] Weight of Terms Represent weight of terms with a term-by-document Matrix, A, where ti denotes term i and dj denotes document j . Entry A(i, j) is computed by TF-IDF . For example: A(0, 0) = (1 / # of terms of d0) * log2(# of docs / t0 occurrences for all docs) = (1/3) * log2(3/2) ~= 0.195 Hence A of the dataset is term\doc d0 d1 d2 t0 0.195 0 0.292 t1 0 0.792 0 t2 0.195 0 0.292 t3 0.195 0.292 0 Note : t0 … t3 can be viewed as a multi-dimension space such that d0 is a point (0.195, 0, 0.195, 0.195) of the space. Document Similarity Per the weight matrix we can compute document-to-document similarities matrix, S, by cosine-similarity. For example: intersect(d0.terms, d0.terms) = ...

PST: Fast Float Serialization

PST: Fast Float Serialization Given float numbers of precision 3 (rounded to decimal places), e.g. 0.123. Following method can de/serialize float numbers safely across platforms of different endianness. // Serialization float number [ 100 ] ; std :: ofstream fout ( “output” ) ; for ( int i = 0 ; i < 100 ; ++ i ) fout << ( number * 1000 ) << endl ; // De-serialization int value ; float result [ 100 ] ; std :: ifstream fin ( “input” ) ; for ( int i = 0 ; i < 100 ; ++ i ) { fin >> value ; result [ i ] = value / 1000.0 ; } By translating float number to a discrete form, the cost of de/serialization (text to double) is reduced since it becomes a text to integer conversion. Original posted in my Tumblr Update: Another technique union { int ival ; float fval ; } number ; number . fval = 0.1234 ; fout << number . ival ; fout >> number . ival ; // use number.fval –...

Getting Started with Google Test and CMake on Windows

Getting Started with Google Test and CMake on Windows Versions Windows 7 MSVC 11 (Visual Studio 2012) CMake 3.0 gtest 1.7.0 Google Test Assume we placed unzipped gtest source in %GTEST_ROOT% . To get gtest-1.7.0 compiled with MSVC11, edit %GTEST_ROOT%\cmake\internal_utils.cmake . macro ( fix_default_compiler_settings_ ) $ if ( MSVC ) $ add_definitions ( - D_VARIADIC_MAX = 10 ) # Add this line # . . . endif ( ) endmacro ( ) Note : You won’t need the workaround with MSVC12, or VS2013 (I envy you). Open up “Developer Command Prompt for VS2012” (yeah, I LOVE cmdline) and type: # Compile cd %GTEST_ROOT% mkdir build cd build cmake .. -G "NMake Makefiles" # Install with prefix "c:\opt" ( change it to whatever you like ) mkdir c:\opt\lib mkdir c:\opt\include xcopy *.lib c:\opt\lib cd .. xcopy include\gtest c:\opt\include\ Note : I actually did files/dirs copying in cygwin and welcome feedback for...

Pyinstaller on Windows

Pyinstaller on Windows Prerequisites 64-bit Windows 2008/7 Python 2.7.10 x86 1 pip virtualenv Microsoft Visual C++ 2008 Redistributable Package (x86) or MSVC Compiler for Pyhton 2.7 2 Create and activate virtualenv virtualenv c:\venv\pyapp cd c:\venv\pyapp\Scripts activate From now on, we’ll be working within a virtualenv environment. PowerShell If you would like to give PowerShell a try like me. Before activate your virtualenv , you need to change your script execution policy via Set-ExecutionPolicy RemoteSigned in a privileged PowerShell terminal. Install pywin32 and pyinstaller easy_install http://sourceforge.net/projects/pywin32/files/pywin32/Build %20219 /pywin32 -219 .win32-py2. 7 .exe /download pip install pyinstaller The msvcr90.dll Problem There is a known issue was discussed on StackOverflow . Quick solution is to install the specific Microsoft Visual C++ 2008 Redistributable Package (x86) which can be downloaded here . If...

ExtJS MVC

ExtJS MVC Architecture Model is persistent in server side. Store is cache of model thru its proxy. Controller connect View and data in Store. Controller responds users’ operations over View. View presents binded data and input widgets to users. Application Files Root Second Third Forth / Fifth Fifth MyApp / + ext-4 /<extjs_code> + index.html + app.js + app / + + controller /Main.js + + model /Main.js + + store /Main.js + + view / + + + Viewport.js + + + main / + + + + Act1.js + + + + Act2.js + data / + + main.json + + updatemain.json index.html < html > < head > < title > Account Manager </ title > <!-- Load ExtJS style sheet and scripts --> < link rel = " stylesheet " type = " text/css " href = " ext-4/resources/css/ext-all.css " > ...

Exception Translation from C++ to Python with Boost.Python

Exception Translation from C++ to Python with Boost.Python Scenario Say we have written a Python binding with Boost.Python. Something like following code. // some.cpp # include <stdexcept> # include <boost/python.hpp> struct my_exception : std :: exception { my_exception ( int extra_info ) : extra_info ( extra_info ) { } char const * what ( ) noexcept ( true ) { return "My exception" ; } int const extra_info ; } ; void do_throw ( ) { throw my_exception ( ) ; } // Something should be done here ... BOOST_PYTHON_MODULE ( MyLib ) { using namespace boost :: python ; def ( "do_throw" , & do_throw ) ; } And we wish to catch a Python exception object in Python code, e.g. import MyLib try : MyLib . do_throw ( ) except MyLib . MyException as e : print e , e . extra_info pass The situation is, we can’t directly pass the exception object, my_exception,...