跳到主要內容

發表文章

目前顯示的是 2020的文章

得利油漆色卡編碼方式

得利油漆色卡編碼方式 類似 Munsell 色彩系統 ,編碼方式為 HUE LRV/CHROMA 例如 10GY 61/449 ( 色卡 ) 編碼數值 描述 10GY hue ,色輪上從 Y(ellow) 到 G(reen) 區分為 0 ~ 99 ,數值越小越靠近 Y,越大越靠近 G 61 LRV (Light Reflectance Value) 塗料反射光源的比率,數值從 0% ~ 100% ,越高越亮,反之越暗,也可理解為明度 449 chroma 可理解為彩度,數值沒有上限,越高顏色純度 (濃度) 越高 取決於測量儀器,對應至 RGB 並不保證視覺感受相同。 參考資料: 色卡對照網站 e-paint.co.uk Written with StackEdit .

Stringify C++ Enum Safely

Stringify Enum Safely Sometimes stringifying C/C++ enumerator, or enum , values within its literal names are useful for debugging or logging. In this article, I’ll share how I achieve basic enum stringify and how to do it safely against changes to enum definitions. Basic Idea Given a boring enum Result as follows. enum class Result : int8_t { OK = 0 , FAILED , } ; My usual way to stringify them is using a table, i.e. # define STR(X) #X char const * StringifyResult ( Result res ) { char const * str [ ] = { STR ( OK ) , STR ( FAILED ) , } ; return str [ static_cast < std :: underlying_type_t < Result >> ( res ) ] ; } int main ( ) { printf ( "%s" , StringifyResult ( Result :: OK ) ) ; // print "OK" } It benefits us from simplicity - simply copy’n paste those enum values then decorate them with STR() . Tons of editors can accomplish such editing in a snap. Check Consistency

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 <