Best C++ macro for creating a new scope -
i have macro
#define scope_guard(guard, name, ...) \ for(bool __once = true; __once; /* nothing */) \ for(guard name (__va_args__); __once; __once = false)
using this:
scope_guard(std::unique_lock, lock, (some_mutex)) do_some();
or
scope_guard(std::unique_ptr<char>, buff, (new char[buffer_size])) { *buff.get() = 0; getsomedescription(buff.get(), buffer_size); log(buff.get); }
are there similar(better) implementation of macro, optimized multiple compilers correctly.
p.s. macro should one, without macro boost_scope_exit_end
(can redefine if (...)
).
edit simple scoupe in using codestyle huge.
{ std::unique_lock lock (some_mutex); do_some(); }
but want using this
scope_guard(std::unique_lock, lock, (some_mutex)) do_some();
you can awful lot c++ templates , lambda expressions. might worthwhile explore using them. example, instead of using scope_guard
macro, this:
template <typename g, typename f, typename... a> inline auto scope_guard(g&&, f&& f, a&&... args) -> decltype(std::forward<f>(f)(std::forward<a>(args)...)) { return std::forward<f>(f)(std::forward<a>(args)...); } scope_guard(std::unique_lock<std::mutex>(m), do_something); scope_guard(std::unique_lock<std::mutex>(m), [&]() { do_something1(); do_something2(); do_something3(); });
if using straight macros, mine this:
#define unwrap(...) __va_args__ #define scope_guard(x, y) { x; unwrap y; } while (0) scope_guard(std::unique_lock<std::mutex> lock(m), (do_something())); scope_guard(std::unique_lock<std::mutex> lock(m), ( do_something1(); do_something2(); do_something3(); ));
Comments
Post a Comment