0

I have the following code:

template <int Size>
    class A
    {
        public: 
            static int size;
            static int myArray[Size];
    };

The size variable I can set by:

template <int Size>
int A<Size>::size=SomeQuantity;

I would like to initialize the array from 0...Size in steps of 1. E.g, if Size=10, myArray =[0,1,2,....,9]

Can the initialization of a static array be assigned to a function? Is there any C++ built in way of doing this?

Edit I could define inside the class:

static int initArray()
{
    for( int i = 0; i<sizeof(myArray)/sizeof(myArray[0]); i++)
    {
        myArray[i]=i;
    }
    return 0;
}

And afterwards initialize this as:

template <int Size>
int A<Size>::myArray[Size]={initArray()};

Kind regards

  • Why not using std vector ? makes life easy no ? – AdityaG Feb 22 '22 at 11:40
  • Agreed. But in this particular case I have to use standard arrays :/ –  Feb 22 '22 at 11:42
  • 1
    @AdityaG People often write code like this to test out how things work and gain knowledge. After all, it could come in handy if some C++ code were written to use an array. Additionally, an array can be the right tool if the size is constant although I'd recommend an `std::array` in that case to benefit from any optimizations that can be done due to a constant size as well as to document the size is constant through the type chosen. With an `std::vector`, you have to wonder if the size changes, and its dynamic nature might be a little slower. – user904963 Feb 22 '22 at 11:58
  • I see. Then as @Kaktuts suggests, making this array as a pointer and using a function to make the memory and to intializie the array is a way to go. – AdityaG Feb 22 '22 at 12:51
  • Even if it is a static array? –  Feb 22 '22 at 12:54
  • I think this answers the question: https://stackoverflow.com/questions/19019252/create-n-element-constexpr-array-in-c11 – nielsen Feb 22 '22 at 14:20

1 Answers1

-1

Write your own function, eg

int* MakeArray(const int size){
    int* res = new int[size];
    //stl generate transform or just a loop
    for (auto i=0;i<size;i++) res[i]=i;
    return res;
}
Kaktuts
  • 86
  • 3
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '22 at 11:59
  • This will give me an error, saying: `invalid conversion from ‘int*’ to ‘int’ [-fpermissive]` –  Feb 22 '22 at 15:21
  • @Thomas Jerry, code is valid . This example: `int* MakeArray(const int size){ int* res = new int[size]; //stl generate transform or just a loop for (auto i=0;i – Kaktuts Feb 24 '22 at 12:53