该机制看起来像:
atomic{// code here}
我不想等待未来的标准我自己试图实现这个,我想出的是:
#define CONCAT_IMPL(A,B) A ## B#define CONCAT(A,B) CONCAT_IMPL(A,B)# define atomic(a) { \static_assert(std::is_same<decltype(a),std::mutex>::value,"Argument must be 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 = [&]()
和用法:
std::mutex mut;atomic(mut){ // code here};}
问题显然是};我想删除.
这有可能吗?
解决方法 您可以使用在if语句中定义变量的技巧来完成此 *** 作.template <typename M>struct atomic_guard_ { explicit atomic_guard_(M& m) : lock(m) {} atomic_guard_(M const&) =delete; // Since we unfortunately have to use uniform atomic_guard_(M&&) =delete; // initialization,make it at least a little safe operator bool() const { return false; } std::lock_guard<M> lock;};#define atomic(m) \ if (atomic_guard_<std::decay<decltype(m)>::type> _{m}) {} elseint main(){ std::mutex m; atomic(m) { std::cout << "a\n"; } atomic(m) // this works too,but I think this is ok std::cout << "b\n";}总结
以上是内存溢出为你收集整理的c – “美化”宏全部内容,希望文章能够帮你解决c – “美化”宏所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)