Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 484
Manoj R Avatar asked Sep 19 '25 18:09

Manoj R


1 Answers

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)
like image 180
Nawaz Avatar answered Sep 22 '25 07:09

Nawaz