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

前端 未结 9 2172
情话喂你
情话喂你 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:12

    You could wrap the one-time action in the constructor of a static object that you instantiate in place of the conditional.

    Example:

    #include 
    #include 
    
    struct do_once {
        do_once(std::function fun) {
            fun();
        }
    };
    
    int main()
    {
        for (int i = 0; i < 3; ++i) {
            static do_once action([](){ std::cout << "once\n"; });
            std::cout << "Hello World\n";
        }
    }
    

    Or you may indeed stick with a macro, that may look something like this:

    #include 
    
    #define DO_ONCE(exp) \
    do { \
      static bool used_before = false; \
      if (used_before) break; \
      used_before = true; \
      { exp; } \
    } while(0)  
    
    int main()
    {
        for (int i = 0; i < 3; ++i) {
            DO_ONCE(std::cout << "once\n");
            std::cout << "Hello World\n";
        }
    }
    

提交回复
热议问题