Re: How to initialise const static char array in a header only class?
On Saturday, September 29, 2012 5:10:58 PM UTC+2, Joost Kraaijeveld wrote:
Hi, I want to initialise a const static char array in a class that
should be header only. The header will be included by many clients
within the same program. [...]
Is this a matter of mere syntax or is this something that cannot
be done?
It's not a matter of syntax. Static data members are NEVER defined in a class definition, only declared. As a special exception, the compiler lets you "initialize" _constant_ _integral_ (or scalars in general?) members.
Or is there another way to get the same effect, without resorting to
a cpp file?
Do you have a good reason for defining an array inside a header? Not requiring a CPP file is not a good reason, IMHO.
But you can do things like
typedef int five_ints[5];
inline const five_ints& foo()
{
static const five_ints arr = {1,2,3,5,8};
return arr;
}
in a header file -- or even write
template<class Dummy=void>
class MessageBase
{
public:
static const int arr[5];
};
template<class Dummy>
const int MessageBase<Dummy>::arr[5] = {1,2,3,5,8};
class Message : public MessageBase<>
{
};
since multiple definitions of inline functions and members of class templates are allowed within a program. But the purpose of these rules is to support templates and to ease inlining. It's not to allow users to define arrays in header files.
Cheers!
SG