I have a number of templatic and inline functions defined in an header file (let's call it head.h
). Currently, these functions use some global variables declared with extern
in the same header and defined somewhere in one .cpp.
Everything works fine, but I would limit global variables scope only to the header where they are defined.
In other words every other .h or .cpp that includes my head.h wouldn't be able to see such globals.
Any way to achieve this result?
One way would be to put a class around it instead of a namespace, making all functions public static methods of that class and the global variables private static variables.
i.e.:
head.h:
class A
{
public:
template <typename T> static void MethodA(T const &value)
{
//...
}
inline static void MethodB(int a, int b)
{
// ...
}
private:
static int x;
static std::string y;
};
head.cpp:
int A::x = 0;
std::string A::y;
EDIT:
Another alternate method would be to define the globals as private static variables in a class and make all functions that are allowed to use them friend functions:
head.h:
template <typename T> void FunctionA(T const &value);
void FunctionB(int a, int b);
class Vars
{
friend template <typename T> void FunctionA(T const &value);
friend FunctionB(int a, int b);
private:
static int x;
static std::string y;
};
template <typename T> void FunctionA(T const &value)
{
// ...
// ... A::x ...
// ...
}
inline void FunctionB(int a, int b)
{
// ...
// ... A::y ...
// ...
}
head.cpp:
int A::x = 0;
std::string A::y;