Reputation: 13936
I don't think this is a duplicate because other questions ask why it's necessary, not how I can avoid writing it twice.
Often with classes I'll introduce member variables and then, for whatever reason, remove them shortly after if I don't like them.
With a non-static member variable I can simply add a member to the header file and use it in my code immediately. With a static member variable I have to do the following:
static int a;
.static
keyword.All of this makes me want to just make all of my classes instantiable and do everything through an object, even if it wouldn't make sense.
So even if this is just a requirement of the language and there is no way around it, is there a way to cut back on the repetition by using macros in some way?
Also I was thinking if maybe it mightn't be simpler to just have one .cpp file containing all of these static member variable definitions. Seeing as though (I've heard) static member variables are basically global variables accessed through a class namespace, is this a better idea than doing it in each corresponding .cpp file?
Upvotes: 2
Views: 280
Reputation: 217478
A possibility is too use static
in function scope, something like:
struct C {
static int& a() {
static int a_instance = 42;
return a_instance;
}
};
Upvotes: 1
Reputation: 234715
I'm going to provide a solution for integral types (since you highlight those types in your question):
struct Foo
{
enum {Value = 123;}
};
Value
can be used as an integral constant, is the same for all instances of Foo
(rather like a static
) and does not require definition in a source file. Note though that &Value
makes no sense, i.e. there's no such thing as a pointer to an enumeration value.
You can do things with constexpr
in later C++ standards (C++11 onwards), but my way is arguably simpler and is also an important metaprogramming technique.
(If this is not sufficient for what you want then please downvote and I'll remove.)
Upvotes: 3