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

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

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

#include 

        
9条回答
  •  -上瘾入骨i
    2020-12-22 22:12

    Like @damon said, you can avoid using std::exchange by using a decrementing integer, but you have to remember that negative values resolve to true. The way to use this would be:

    if (static int n_times = 3; n_times && n_times--)
    {
        std::cout << "Hello world x3" << std::endl;
    } 
    

    Translating this to @Acorn's fancy wrapper would look like this:

    struct n_times {
        int n;
        n_times(int number) {
            n = number;
        };
        explicit operator bool() {
            return n && n--;
        };
    };
    
    ...
    
    if(static n_times _(2); _)
    {
        std::cout << "Hello world twice" << std::endl;
    }
    

提交回复
热议问题