Tags: , | Categories: ツール, ソフトウェア開発 Posted by usagi on 2010/07/19 5:14 | コメント (0)

前回のN 以下で最大のBのべき乗Rを得る wrp::math::max_power_oflibwrpに追加した後、コンパイル時に定数として解決されていた方がコンパイラの最適化的に嬉しい状況に対応する為、テンプレートメタプログラミング版もコードしてみました。libwrpmath.hxxにtmp::max_power_of_2として追加しました。
(2のべき乗以外はややこしくなる気がするので必要になったら考えようと思います。)

<使用例>

C++, using GeSHi 1.0.8.8
  1. #include <wrp/math.hxx>
  2.  
  3. int main()
  4. {
  5. return wrp::math::tmp::max_power_of_2<640>::result;
  6. }
Parsed in 0.011 seconds at 8.65 KB/s

VC++10.0でコンパイル、実行すると、

プログラム '[2756] CodeTest.exe: ネイティブ' はコード 512 (0x200) で終了しました。

と、言うわけで640以下で最大の2のべき乗512が求められています。

<実装>

C++, using GeSHi 1.0.8.8
  1. template<size_t N>
  2. struct max_power_of_2
  3. {
  4. private:
  5. template<size_t N, size_t C, size_t R>
  6. struct f_
  7. {
  8. private:
  9. static const size_t c2 = C << 1;
  10. public:
  11. static const size_t result = f_<N, c2, N / c2>::result;
  12. };
  13.  
  14. template<size_t N, size_t C>
  15. struct f_<N, C, 1>
  16. {
  17. static const size_t result = C;
  18. };
  19.  
  20. public:
  21. static const size_t result = f_<N, 1, N>::result;
  22. };
Parsed in 0.017 seconds at 22.39 KB/s

与えられたNに対し、C=2^r {r: 0, 1, 2, …}の商を再帰的に求め、商が1となった時のCを返します。

コメント可能な期間を過ぎました