gpt4 book ai didi

c++ - "Beautifying"宏

转载 作者:太空狗 更新时间:2023-10-29 19:44:06 31 4
gpt4 key购买 nike

观看 Herb Sutter 关于 C++ 及以后的原子学的演讲,我瞥见了他关于一种易于使用的锁定/解锁机制的想法,该机制可能会或可能不会出现在未来的语言标准中。

机制看起来像:

atomic{
// code here
}

不想等待 future 的标准,我尝试自己实现这个,我想出的是:

#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 << "a\n";
}

atomic(m) // this works too, but I think this is ok
std::cout << "b\n";
}

关于c++ - "Beautifying"宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990946/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com