array of 2s power using template in c++

萝らか妹 提交于 2019-12-24 00:18:36

问题


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.


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/9531645/array-of-2s-power-using-template-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!