Re: Initialize static members outside the class
On Jul 15, 3:54 pm, Steven Woody <narkewo...@gmail.com> wrote:
On Jul 15, 9:11 pm, James Kanze <james.ka...@gmail.com> wrote:
On Jul 15, 12:05 pm, Steven Woody <narkewo...@gmail.com> wrote:
[...]
Anyway, methods like
td::vector<int> NonPOD::foo(SIZE,4.4)
or
std::vector< int > const Class::staticVect(
begin( something), end( something) )
simply don't work since they both get too much limitation. What I
need to put into the vector in initial time is very specific data,
filling the vector with many default value or a regular serial is not
enought.
But what is the specific data? If it's known at compile time
(or even if it's not---"something" can be an istream_iterator),
you can use the second. And if you don't know it until after
entering main, you can't make the vector const.
If all above is what C++ can do for the specific problem, it
is a shame of the language, but I don't believe it can be
true.
Well, I've yet to find a case where the template constructor
taking two iterators wouldn't work (and the data was known
before hand, of course). And you can always use something like:
std::vector< int > const Class::staticVector(
someFunctionReturningAVectorOfInt() ) ;
Which allows practically anything.
(Vector is, of course, an example; most of the time, for const
objects with static lifetime, I'll just use a C style array,
preferrably of POD type, to avoid any possible order of
initialization issues. But I regularly initialize static
std::map<> const using the two iterator constructor.)
We must did the following work in C for many many times:
// file: foo.c
static const int my_magic_code_table [] {
1,
9,
103,
2,
...
};
Well, that works in C++ as well, and I often use it.
Now I sure you see what I was looking for is just a equivalent
of above in C++ as simple as we can approach. Anything else?
At present, it's not possible to just list the entries directly
if the container type has a constructor. (Note that
boost::array doesn't have a constructor, explicitly to allow
this type of initialization. But it does require that you state
the size up front.) The next version of the standard should
support something similar, but in the meantime, you need the
extra object:
namespace {
int const initializers[] = {
// ...
} ;
}
std::vector< int > const Class::staticMember(
begin( initializers ), end( initializers ) ) ;
(With, of course, the usual definitions for begin and end:
template< typename T, size_t N >
T*
begin( T (&array)[ N ] )
{
return array ;
}
template< typename T, size_t N >
T*
end( T (&array)[ N ] )
{
return array + N ;
}
But you should already have those in your tool kit.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34