c – “美化”宏
发布时间:2020-12-16 10:32:57 所属栏目:百科 来源:网络整理
导读:观看Herb Sutter在C及以后的关于原子的讨论我瞥见了他的一个易于使用的锁定/解锁机制的想法,该机制可能会或可能不会出现在该语言的未来标准中. 该机制看起来像: atomic{// code here} 我不想等待未来的标准我自己试图实现这个,我想出的是: #define CONCAT_
观看Herb Sutter在C及以后的关于原子的讨论我瞥见了他的一个易于使用的锁定/解锁机制的想法,该机制可能会或可能不会出现在该语言的未来标准中.
该机制看起来像: 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}) {} else int main() { std::mutex m; atomic(m) { std::cout << "an"; } atomic(m) // this works too,but I think this is ok std::cout << "bn"; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |