top | item 46410354

(no title)

troglo-byte | 2 months ago

    #include <iostream>
    #define RemParens_(VA) RemParens__(VA)
    #define RemParens__(VA) RemParens___ VA
    #define RemParens___(...) __VA_ARGS__
    #define DoConcat_(A,B) DoConcat__(A,B)
    #define DoConcat__(A,B) A##B
    #define defer(BODY) struct DoConcat_(Defer,__LINE__) { ~DoConcat_(Defer,__LINE__)() { RemParens_(BODY) } } DoConcat_(_deferrer,__LINE__)

    int main() {
        {
            defer(( std::cout << "Hello World" << std::endl; ));
            std::cout << "This goes first" << std::endl;
        }
    }

discuss

order

rezonant|2 months ago

Why would that be preferable to just using an RAII style scope_exit with a lambda

troglo-byte|2 months ago

Meh, I was going to use the preprocessor for __LINE__ anyways (to avoid requiring a variable name) so I just made it an "old school lambda." Besides, scope_exit is in C++23 which is still opt-in in most cases.

pelorat|2 months ago

And here I thought we were trying to finally kill off pre-processor macros.

chuckadams|2 months ago

"We have syntax macros at home"