使用整数模板参数时,可以展开一个循环吗?

编程入门 行业动态 更新时间:2024-10-26 21:20:18
本文介绍了使用整数模板参数时,可以展开一个循环吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码:

template <int size> inline uint hashfn( const char* pStr ) { uint result = *pStr; switch ( size ) { case 10: result *= 4; result += *pStr; case 9: result *= 4; result += *pStr; ... ... case 2: result *= 4; result += *pStr; } return result; }

此代码是某些长度的DNA序列的哈希函数,其中长度是模板参数.这是一个带有switch语句的展开循环,可在正确的位置跳转. 但是大小是一个常数,因为它是模板参数. 我可以专门针对某些尺寸值吗? 也许像这样:

This code is a hash function for DNA sequences of certain lenghts where the length is a template parameter. It is an unrolled loop with a switch statement to jump in at the right spot. The size is however a constant since it is a template parameter. Could I specialize this for certain size values? Maybe with something like:

template <int 2> inline uint hashfn( const char* pStr ) { uint result = *pStr; result *= 4; ++pStr; result += *pStr; return result; }

推荐答案

我倾向于使用模板递归地进行操作.

I would tend to do it recursively with templates.

例如:

template<class TOp,int factor> struct recursive_unroll { __forceinline static void result( TOp& k ) { k(); recursive_unroll<TOp,factor-1>::result( k ); } }; template<class TOp> struct recursive_unroll<TOp,0> { __forceinline static void result( TOp& k ) {} }; struct op { op( const char* s ) : res( 0 ), pStr( s ) {} unsigned int res; const char* pStr; __forceinline void operator()() { res *= 4; res += *pStr; ++pStr; //std::cout << res << std::endl; } }; char str[] = "dasjlfkhaskjfdhkljhsdaru899weiu"; int _tmain(int argc, _TCHAR* argv[]) { op tmp( str ); recursive_unroll<op,sizeof( str ) >::result( tmp ); std::cout << tmp.res << std::endl; return 0; }

这会为我生成最佳代码.如果没有 __ forceinline ,则无法正确内联代码.

This produces optimal code for me. Without __forceinline the code is not properly inlined.

在使用此类优化之前,您应该始终对代码进行测试.然后,您应该查看程序集并解密编译器已经为您完成的工作.但是在这种情况下,(对我而言)似乎有所助益.

You should always bench your code before using such optimizations. And then you should look at the assembly and decipher what your compiler already does for you. But in this case, it seems to be an boost (for me).

__ forceinline 是Microsoft Visual Studio特定的扩展.编译器应生成最佳代码,但并非如此.所以在这里我用了这个扩展名.

__forceinline is a Microsoft Visual Studio specific extension. The compiler should generate optimal code, but for this it doesn't. So here I used this extension.

更多推荐

使用整数模板参数时,可以展开一个循环吗?

本文发布于:2023-11-26 12:28:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   模板   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!