//finally for c++
//endofscope.h
#ifndef __ENDOFSCOPE_H_
#define __ENDOFSCOPE_H_
template<typename T>
struct __EndOfScope
{
T func;
__EndOfScope(T f):func(f){}
~__EndOfScope()
{
func();
}
};
#define __EndOfScopeCONCATE(a,b) a##b
#define __EndOfScopeEOS(a,b) __EndOfScopeCONCATE(a,b)
/*
Call something when the scope ends.
*/
#define EndOfScope(function) auto __EndOfScopeEOS(eos,__LINE__) = function; __EndOfScope<decltype(__EndOfScopeEOS(eos,__LINE__))> __EndOfScopeEOS(eosCaller,__LINE__) (__EndOfScopeEOS(eos,__LINE__) );
#endif //__ENDOFSCOPE_H_
//main.cpp
#include <iostream>
void endOfScopeFunction()
{
std::cout << "End of scope function" << std::endl;
}
int main(int argc, char* argv[])
{
//call a lambda at the end of the scope.
EndOfScope([&](){std::cout << "End of scope lambda" << std::endl;});
//call a lambda at the end of the scope.
auto a2 = [&](){std::cout << "End of scope lambda 2" << std::endl;};
EndOfScope(a2);
//call a functor at the end of the scope.
struct endOfScopeFunctor
{
void operator()()
{
std::cout << "End of scope obj" << std::endl;
}
};
EndOfScope(endOfScopeFunctor());
//call a function at the end of the scope.
EndOfScope(endOfScopeFunction);
//This will be executed first.
std::cout << "The rest of the main !" << std::endl;
return 0;
}
Output :
The rest of the main !
End of scope function
End of scope obj
End of scope lambda 2
End of scope lambda