使用c ++模板的2s幂数组

时间:2012-03-02 10:23:54

标签: c++ templates metaprogramming

我们可以在编译时使用c ++中的模板创建以下数组或类似的东西。

int powerOf2 [] = {1,2,4,8,16,32,64,128,256}

这是我最接近的。

template <int Y> struct PowerArray{enum { value=2* PowerArray<Y-1>::value };};

然后使用我需要像PowerArray&lt; i&gt;这样的东西。哪个编译器给出错误,因为我是动态变量。

2 个答案:

答案 0 :(得分:3)

您可以使用BOOST_PP_ENUM

#include <iostream>
#include <cmath>
#include <boost/preprocessor/repetition/enum.hpp>

#define ORDER(z, n, text) std::pow(z,n)

int main() {
  int const a[] = { BOOST_PP_ENUM(10, ORDER, ~) };
  std::size_t const n = sizeof(a)/sizeof(int);
  for(std::size_t i = 0 ; i != n ; ++i ) 
    std::cout << a[i] << "\n";
  return 0;
}

输出ideone

1
2
4
8
16
32
64
128
256
512

此示例是修改后的版本(以满足您的需要):

答案 1 :(得分:0)

没有什么可以反对使用BOOST_PP_ENUM,但我认为你需要更多我会告诉你的代码。

我会做的是,我会创建一个类型类的构造函数,它只是将数组设置为你需要的东西。这样一来,它就会在程序构建时立即执行,并且保持良好和整洁。 AKA正确的方式。

     class Power
    {
    public:
         Power();
         void Output();
         // Insert other functions here
    private:
         int powArray[10];
    };

然后,实现将使用基本的“for循环”将它们加载到刚刚创建的数组中。

Power::Power()
{
    for(int i=0;i<10;i++){
         powArray[i] = pow(2,i);
    }
}
void Power::Output()
{
     for(int i=0;i<10;i++){
          cout<<powArray[i]<<endl;
     }
}

希望这会有所帮助......