帮助模板化字节交换函数,性能受到影响?
template<int size>
inline void* byteswap(void* __x);
template<>
inline void* byteswap<2>(void* __x)
{
return (*(uint16*)__x >> 8) | (*(uint16*)__x << 8);
}
template<>
inline void* byteswap<4>(void* __x)
{
return (byteswap<4>(__x & 0xffff) << 16) | (bswap_16 (__x >> 16));
}
template<typename T>
inline T byteswap(T& swapIt)
{
return (T*)byteswap<sizeof(T)>(swapIt);
}
int main() {
uint32 i32 = 0x01020304;
uint16 i16 = 0x0102;
byteswap(i32);
byteswap(i16);
return 0;
}
上面的内容显然无法编译。我很困惑,因为似乎我需要 void* 作为函数的参数,而 byteswap<4> 中的事情有点丑陋。当我需要调用 byteswap<2> 时但有参考。
知道如何让它看起来漂亮吗?它是否有可能实现(使用内联或其他技巧)使其性能与直接进行位操作一样?
template<int size>
inline void* byteswap(void* __x);
template<>
inline void* byteswap<2>(void* __x)
{
return (*(uint16*)__x >> 8) | (*(uint16*)__x << 8);
}
template<>
inline void* byteswap<4>(void* __x)
{
return (byteswap<4>(__x & 0xffff) << 16) | (bswap_16 (__x >> 16));
}
template<typename T>
inline T byteswap(T& swapIt)
{
return (T*)byteswap<sizeof(T)>(swapIt);
}
int main() {
uint32 i32 = 0x01020304;
uint16 i16 = 0x0102;
byteswap(i32);
byteswap(i16);
return 0;
}
The above obviously doesn't even compile. I'm confused as it seems that I need void* as parameter for the function and things kinda get ugly in byteswap<4> when I need to call byteswap<2> but with a reference.
Any idea how to make this look pretty? Is it possible for it to achieve (using inlining or other tricks) to make it as performance as doing the bit-operations directly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是我的编码方式:
换句话说,我不会像您那样使用 size 作为模板参数。
编辑
抱歉,我的第一个代码在 rt/uint32 交换方面是完全错误的。
This is how I'd code it:
in other words, I wouldn't use size as template parameter as you were doing.
EDIT
sorry, my first code was plain wrong wrt/ uint32 swapping.
借用一些代码:
Borrowing from some code:
我会这样重写:
I'll rewrite it like that:
我认为您对 byteswap(2) 和 byteswap(4) 的定义在概念上是错误的。我认为你定义的方式不正确,请参考网址
http://www.iis.sinica.edu.tw/ 〜凯西/vcstl/templates.htm#T6
i think you are conceptually wrong as definitions of byteswap(2) and byteswap(4) . i dont think the way you defined is right plase refer to url
http://www.iis.sinica.edu.tw/~kathy/vcstl/templates.htm#T6