其他分享
首页 > 其他分享> > 如何将此c模板函数转换为C替代?

如何将此c模板函数转换为C替代?

作者:互联网

我正在将一个小C库的部分转换为C(gcc).在这样做时,我想将以下模板函数转换为宏(为了可读性而删除了注释). CpuReadWriteFence()是我成功转换为宏的另一个函数.

template<typename T>
static inline T AtomicLoadAcquire(T const* addr)
{
    T v = *const_cast<T const volatile*>(addr);
    CpuReadWriteFence();
    return v;
}

由于C中没有模板,我使用的是函数或宏. GCC提供了一个
方便的扩展类型.也许我可以用void *做到这一点?如果是这样的话?

到目前为止我所拥有的是:

#define AtomicLoadAcquire(addr)                                       \
    ({ typeof (addr) v = *(volatile typeof (addr) *)(addr); CpuReadWriteFence(); })

但是,这不允许我这样做:

int x = AtomicStoreRelease(&bla);

我怎么能绕过这个?

解决方法:

你几乎做对了. GCC “statements and declarations in expressions”扩展不必返回void.

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)

因此,您可以将宏定义为:

#define AtomicLoadAcquire(addr)                                       \
({ typeof (*addr) v = *(volatile typeof (addr) )(addr); CpuReadWriteFence(); v; })

注意v;在宏的最后.这就是魔术的来源.

另请注意,第一个类型将* addr作为参数,并且在volatile类型(addr)之后没有星号.那些是与你的主要问题无关的一些小错误.

标签:c-3,equivalent,c,templates,gcc
来源: https://codeday.me/bug/20190729/1575597.html