從one_of說起
之前寫過這樣的 Code Snippet
1 |
|
這程式碼適用於C++11,如果用C++17可以用fold expression
更進一步簡化
1 | enum state_type { IDLE, CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED }; |
能不能更進一步?
variadic non type template
1 | enum state_type { IDLE, CONNECTING, CONNECTED, DISCONNECTING, DISCONNECTED }; |
可以看出,這個版本將比較值跟貝比教值分開,比原先的版本更容易看出語意,不過問題也很明顯,所以被比較值要在編譯期就決定了,靈活度反而比不上原先的方案,有沒有折衷的方案?
std::tuple
看到Modern Techniques for Keeping Your Code DRY這方案真是眼睛一亮
1 | template <typename ...Ts> |
用CTAD,std::tuple,std::apply的組合技包裝成威力十足的武器
Add more operation
假設我們現在要加上<
的比較
1 | template <typename ...Ts> |
可以看出兩段程式碼大同小異,能否亙進一步?
Higher order functions
由於兩個operator都是由一系列or operation組成的
因此我們可以把or operation提出來
1 | template <typename F, typename ...Ts> |
至此any_of的東西就差不多了,那麼來寫all_of吧
all_of implementation
大同小異
1 | template <typename F, typename ...Ts> |
一般來說做到此就行了,能否亙進一步?
Inheritance
再上去就是炫技了,實用度就不高了,編譯時間又拉長不少
1 | struct or_elements { |
Reference
– Modern Techniques for Keeping Your Code DRY
– Lambdas: From C++11 to C++20, Part 1
– Lambdas: From C++11 to C++20, Part 2