Skip to main content

Posts

Showing posts from December, 2021

Bind lambda with a class and execute while class instance destroys (A final pattern)

 Let's have a template class like below: template< typename T > class finalGuard {     T m_func; public:     finalGuard(T func) : m_func(func) {}     ~finalGuard() { m_func(); } }; What is the requirement? I need to execute lambda when a template instance of the above class goes out of scope or any exception is caused during the execution of code. We can think of this as more or like a final pattern. When a class object's lifetime ends, a piece of code will start executing to wrap up things.  Now I have a factory-like function defined as below to resolve type dependency which lambda is expecting: template< typename T > finalGuard< T > finalCall(T obj) { return obj; }  The below piece of code is used to bind the lambda with the class instance and it gets executed as soon as a class object destructor gets invoked. int main() {     try {         auto guard = finalCall([]() noexcept {     ...