array of 2s power using template in c++

Can we create the following array or something similar using template in c++ at compile time.

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

This is the closest I got.

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

but then to use I need something like PowerArray <i> which compiler gives error as i is dynamic variable.


You can use BOOST_PP_ENUM for this:

#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;
}

Output ideone:

1
2
4
8
16
32
64
128
256
512

This example is a modified version (to suit your need) of this:

  • Trick : filling array values using macros (code generation)

  • Nothing against using BOOST_PP_ENUM but I think your going for more of the kind of code I will show you.

    What I would do, is I would make a constructor of your type class which just sets the array to the stuff you need. That way it does it as soon as the program builds and it stays nice and neat. AKA the proper way.

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

    Then the implementation would be with a basic "for loop" to load them into the array you just created.

    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;
         }
    }
    

    Hopes this helps...

    链接地址: http://www.djcxy.com/p/62692.html

    上一篇: 在汇编程序中访问数组成员

    下一篇: 使用c ++模板的2s电源阵列