r/cpp • • Feb 24 '26

Clang 22 Release Notes

https://releases.llvm.org/22.1.0/tools/clang/docs/ReleaseNotes.html

LLVM 22 was released, update your toolchains!

https://discourse.llvm.org/t/llvm-22-1-0-released/89950

114 Upvotes

27 comments sorted by

View all comments

Show parent comment

10

u/pavel_v Feb 25 '26

You can use macro (yeah, I know) and get pretty close (few characters more to type).

Something like this:

namespace smth
{

template <typename Func>                                                        
class scope_guard 
{ ... };

namespace detail                                                                
{                                                                               
    enum class scope_guard_on_exit {};                                          
                                                                                
    template <typename Func>                                                    
    auto operator +(scope_guard_on_exit, Func&& func)                           
    {                                                                           
        return scope_guard<Func>(std::forward<Func>(func));                     
    }                                                                           
}                                                                               
                                                                                
} // namespace smth                                                                                                                        
                                                                                
#define CONCAT_STR_IMPL(s1, s2) s1##s2                                     
#define CONCAT_STR(s1, s2) CONCAT_STR_IMPL(s1, s2)                    
#define ANONYMOUS_VAR(s) CONCAT_STR(s, __COUNTER__)                                                                                              
#define DEFER \                                                       
    auto ANONYMOUS_VAR(defer_var) = smth::detail::scope_guard_on_exit() + [&]()

Then use it like

DEFER { CoUninitialize(); };

Disclaimer: It's "stolen" from this talk of Alexandrescu.

7

u/fdwr fdwr@github 🔍 Feb 25 '26

Oh the beautiful horrors that macros enable, 😉 cutting the extra line noise down from =()(){}[]; to just {};) I look forward to the future beautiful horrors that reflection enables... 😂