W
werasm
I'd like to write all code of a class in only header file. But when
there is any static member varia ble, I have to define it in cpp file,
not the header file. Otherwise, the static member variable may be
duplicated because two or more cpp files may include the header.
How can I solve this without the cpp file, which used to define the
static member variable?
Thanks!
I agree with most of what everyone has said, therefore <this> solution
to your problem is not worth much I deem, but it may be considered:
template <class T, class U>
struct HasStaticVar
{
static U get;
};
template <class T,class U>
U HasStaticVar<T,U>::get = U();
struct X : HasStaticVar<X,int>
{
};
int main()
{
X::get = 20;
return 0;
}
Of course, you could make the static member protected
so as to only allow change via derived. If the member
is something other than builtin, you would have to use
interesting schemes to initialize it to something other
than its default. etc. Nevertheless, X has its static
variable.
Kind regards,
Werner