3

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.

Manoj R
  • 3,197
  • 1
  • 21
  • 36

2 Answers2

3

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:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

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...

VERNSTOKED
  • 107
  • 1
  • 1
  • 10