Tuesday, 15 January 2013

c++ - "Beautifying" macro -



c++ - "Beautifying" macro -

watching herb sutter's talk atomics @ c++ , beyond glimpsed @ thought of easy utilize lock/unlock mechanism may or may not come in future standard of language.

the mechanism looks likes:

atomic{ // code here }

not wanting wait future standard tried implementing myself, i've come this:

#define concat_impl(a, b) ## b #define concat(a, b) concat_impl(a, b) # define atomic(a) { \ static_assert(std::is_same<decltype(a), std::mutex>::value,"argument must of type std::mutex !");\ struct concat(atomic_impl_, __line__)\ {\ std::function<void()> func;\ std::mutex* impl;\ concat(atomic_impl_, __line__)(std::mutex& b)\ { \ impl = &b;\ impl->lock();\ }\ concat(~atomic_impl_, __line__)()\ { \ func();\ impl->unlock(); \ }\ } concat(atomic_impl_var_, __line__)(a);\ concat(atomic_impl_var_, __line__).func = [&]()

and usage:

std::mutex mut; atomic(mut){ // code here };}

the problem, obviously, }; i'd remove.

is possible in way?

you can trick of defining variables within if statement.

template <typename m> struct atomic_guard_ { explicit atomic_guard_(m& m) : lock(m) {} atomic_guard_(m const&) =delete; // since unfortunately have utilize uniform atomic_guard_(m&&) =delete; // initialization, create @ to the lowest degree little safe operator bool() const { homecoming false; } std::lock_guard<m> lock; }; #define atomic(m) \ if (atomic_guard_<std::decay<decltype(m)>::type> _{m}) {} else int main() { std::mutex m; atomic(m) { std::cout << "a\n"; } atomic(m) // works too, think ok std::cout << "b\n"; }

c++ c++11 macros

No comments:

Post a Comment