I wonder if it is possible to initialize an entire array with a constexpr function (with C++ 2011).
Here I have something to illustrate what I want to do :
template<unsigned int DIM> const unsigned int MyClass<DIM>::_myVar[2][3] = {
{metaFunction(0, 0, DIM), metaFunction(0, 1, DIM), metaFunction(0, 2, DIM)},
{metaFunction(1, 0, DIM), metaFunction(1, 1, DIM), metaFunction(1, 2, DIM)}
};
template<unsigned int DIM> inline constexpr unsigned int MyClass<DIM>::metaFunction(const unsigned int k, const unsigned int n, const unsigned int dim)
{
return (((n < dim) && (k < n)) ? (1<<(n-k)) : (0));
}
Is there a way to initialize myVar with a constexpr without filling the array manually. And if it exists, what would be the syntax for the given example ?
To precise the question a little, I search for a way to fill all values of myVar using a single function call.
Without seeing the definition of
MyClassthe problem is not quite clear.I believe anyway that you want to get
MyClass::_myVarinitialized withoutcode to iteratively fill it with the
MyClass::metaFunction()values.You code suggests that
MyClass::_myVaris a static class member. In thatcase your initialization of the member is perfectly good C++11 as it stands.
The following program illustrates (GCC 4.6.3):
This inclines me to think that
MyClass::_myVaris not a static member –although why this array of integer constants would not be static I am not sure.
If that is the case, then you can initialize the member in the default
constructor using the uniform initialization provision of C++11:
In neither case is the
constexprattribute ofmetaFunctionactuallynecessary for compilation. And if
constexpris removedthen
/* MyClass Version 1*/is also good for C++03.