【C++】A trick I learned:put boilerplate code into constructor of a struct

I learned this trick from hitonanode's submission on AtCoder.

The trick is like

struct fast_ios { 
      fast_ios(){ 
            cin.tie(0); 
            ios::sync_with_stdio(false); 
            cout << fixed << setprecision(20); 
      }
} fast_ios_;

What I used to do is like

#define FAST_READ ios::sync_with_stdio(false); cin.tie(nullptr);
int main() {
    FAST_READ
    cout << fixed << setprecision(10);
    // ...
}

using this trick, the code becomes

struct fast_ios { fast_ios(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(10); } } fast_ios_;
int main() {
    // ...
}

I think macros are better avoided when alternatives are available.

Update 2020/5/21
There is another way to achieve the same function:

int fast_io = []() {
            cin.tie(0); 
            ios::sync_with_stdio(false); 
            cout << fixed << setprecision(20); 
            return 0;
}();
posted @ 2019-11-05 09:59  Pat  阅读(148)  评论(0编辑  收藏  举报