加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:39:00 所属栏目:百科 来源:网络整理
导读:我正在将一个小C库的部分转换为C( gcc).在这样做时,我想将以下模板函数转换为宏(为了可读性而删除了注释). CpuReadWriteFence()是我成功转换为宏的另一个函数. templatetypename Tstatic inline T AtomicLoadAcquire(T const* addr){ T v = *const_castT con
我正在将一个小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)之后没有星号.那些是与你的主要问题无关的一些小错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读