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?
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.
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];
}
}
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With