如何预先计算值数组?

时间:2008-11-07 16:22:58

标签: c++ templates

有没有办法根据模板预先计算一组值?在下面的示例中,我希望'powers_of_2'数组在编译时计算256个值,如果可以的话,无需键入所有值。

#include <iostream>
using namespace std;

template <int X, char Y>
struct power {
   enum { value = X * power<X,Y-1>::value };
};

template <int X>
struct power<X,1> {
   enum { value = X };
};

template <int X>
struct power<X,0> {
   enum { value = 1 };
};

int _tmain(int argc, _TCHAR* argv[])
{
   int powers_of_2[] = { power<2,0>::value, power<2,1>::value, ..., power<2,255>::value };
   cout << powers_of_2[1] << endl;
   return 0;
}

6 个答案:

答案 0 :(得分:4)

除非你打算使用一个大整数包,否则你将在2 ^ 32(或2 ^ 64,取决于)时溢出整数类型,但要回答你的真实问题,请查看template metaprogramming上的这篇维基百科文章。 / p>

答案 1 :(得分:1)

这正是宏对...有用的东西。

答案 2 :(得分:1)

保持值2 ^ 255将需要32个字节。这不能在int中保存;你需要一个char数组

typedef unsigned char BYTE32[32];
BYTE32 powers_of_2[256] =
{
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,128},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
  {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0},
// :
// :
  {32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
  {128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
};

答案 3 :(得分:1)

我在这种情况下所做的是编写一个小程序,在C ++源代码中生成并写入数组初始化文件,然后#include该文件。这种技术简单有效。

答案 4 :(得分:0)

您可以使用首选的脚本语言轻松编写一个小脚本来为您预填充数组。根据您使用的编译器和预处理器,您还应该能够以宏的形式进行操作。

答案 5 :(得分:0)

我同意Lokkju。仅通过模板元编程来初始化阵列是不可能的,并且在这种情况下宏是非常有用的。甚至Boost库也使用宏来实现重复的语句。

有用的宏示例如下:http://awgn.antifork.org/codes++/macro_template.h