Since C++ 17 one can write an if
block that will get executed exactly once like this:
#include
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;
}