It is very convenient to use namespaces over classes filled with static members. This answer show some benefits, but what I really like are:
- You can create variables that are global within the translation unit (file), but not accessible outside. Essentially like a private variable.
- Added benefit is that, every time you modify the private variable, you won’t need to potentially recompile multiple header files but just single source file, which keeps me sane.
There are other stuff mentioned but I just want to focus on these 2.
In general I’ve been fine with only using namespaces for that. However, recently I’ve decided that a particular source file was getting too big and I decided to split into two.
// Foo.h
namespace foo{
void increase();
void decrease();
}
// Foo.cpp
namespace foo{
int foo = 0;
int bar = 0;
void increase(){
bar++;
foo++;
}
void decrease(){
bar--;
foo--;
}
}
Suppose into the splitting part:
// FooIncremental.cpp
namespace foo{
// global variables here...?
void increase(){
bar++;
foo++;
}
}
// FooDecremental.cpp
namespace foo{
// global variables here...?
void decrease(){
bar--;
foo--;
}
}
Now I run into a problem to create a functional source file because I can’t create a global variable that are restricted to two files (benefit 1)
However, if we were to create “static” classes:
// Foo.h
struct foo{
static void increase();
static void decrease();
private:
static int foo;
static int bar;
}
// FooIncremental.cpp
int foo = 0;
int bar = 0;
void foo::increase(){
bar++;
foo++;
}
// FooDecremental.cpp
void foo::decrease(){
bar--;
foo--;
}
that will work, and I can probably further split over. However I will lose the benefit 2.
Is there a solution for this, that can allow me to keep benefits 1 and 2 at the same time?
5