Most elegant way to write a one-shot 'if'

前端 未结 9 2154
情话喂你
情话喂你 2020-12-22 21:51

Since C++ 17 one can write an if block that will get executed exactly once like this:

#include 

        
9条回答
  •  独厮守ぢ
    2020-12-22 22:00

    static bool once = [] {
      std::cout << "Hello one-shot\n";
      return false;
    }();
    

    This solution is thread safe (unlike many of the other suggestions).

提交回复
热议问题