Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Fill array according to template parameter

Essentially, the situation is as follows:

I have a class template (using one template parameter length of type int) and want to introduce a static array. This array should be of length length and contain the elements 1 to length.

The code looks as follows up to now:

template<int length>
class myClass{
    static int array[length];
};

Then I wanted to write a line for initalizing the array

// of course, the line below does not work as intended.
template<int length> int myClass<length>::array[length]={1,2, ..., length};

(How) can this be achieved?

like image 559
phimuemue Avatar asked Jul 01 '10 11:07

phimuemue


3 Answers

You can't do that with C-style arrays because they don't have value semantics.

If you use something like std::tr1::array however then you could easily do what you want by initialising to a function result, or by using an iterator that generates those values.

like image 143
Peter Alexander Avatar answered Oct 29 '22 17:10

Peter Alexander


Use "static constructor" idiom.

// EDIT 2

#include <iostream>

template<int length>
class myClass {
public:
    typedef int ArrayType[length];

    static struct StaticData {
        ArrayType array;

        StaticData()
        {
            for (int i = 0; i < length; i++) array[i] = i;
        }
    }
    static_data;

    static ArrayType &array;
};

template<int length>
typename myClass<length>::StaticData myClass<length>::static_data;

template<int length>
typename myClass<length>::ArrayType &myClass<length>::array = myClass<length>::static_data.array;

int main(int argc, char** argv) {
    const int LEN = 5;
    for (int i = 0; i < LEN; i++) {
        std::cout << myClass<LEN>::array[i];
    }
}
like image 44
adf88 Avatar answered Oct 29 '22 18:10

adf88


You can write a wrapper class, but I'm sure there are cleaner solutions:

template <size_t length>
class array_init_1_to_n
{
    int array[length];

public:

    array_init_1_to_n()
    {
        for (int i = 0; i < length; ++i)
        {
            array[i] = i + 1;
        }
    }

    operator int*()
    {
        return array;
    }

    operator const int*() const
    {
        return array;
    }
};

template<size_t length>
class myClass{
    static array_init_1_to_n<length> array;
};
like image 1
fredoverflow Avatar answered Oct 29 '22 18:10

fredoverflow