top | item 43961399

(no title)

Sebb767 | 9 months ago

> * Defer has an overloaded operator%. It's a template function, which takes a callable object (type is the template parameter Callable) and returns a DeferHolder<Callable> instance.

Is there any reason to use operator% instead of a normal method call? Except possibly looking cool, which doesn't seem useful given that the call is hidden away in a macro anyway.

discuss

order

quietbritishjim|9 months ago

If you used a normal method call then there would need to be a corresponding close bracket at the end of the overall line of code, after the end of the lambda function. But the macro ("defer") only occurs at the start of the line, so it has no way to supply that close bracket. So the caller of the macro would have to supply it themselves. As I mentioned near the end of my comment, it seems like the defer macro is specifically engineered to avoid the caller needing a close bracket.

If you don't mind that, I said that you can "simplify the implementation" - what I meant was, as you say, you don't need the overloaded Defer::operator% (or indeed the Defer class at all). Instead you could do:

   template <typename Callable>
   DeferHolder<Callable> _get_defer_holder(Callable&& cb) {
       return DeferHolder<Callable>{std::forward<Callable>(cb)};
   }
   #define DEFER(my_lambda) auto COMMON_CAT(_defer_instance_, __LINE__) = _get_defer_holder(my_lambda)
Disclaimer: I haven't tried it and I don't normally write macros so this could have glaring issues.