Reputation: 4022
I am writing a namespace that requires certain functions inside to have access to a particular variable (also declared within the namespace). Normally when I do this, I have the variable declared in the .cpp file to prevent outside access to it.
.h
namespace Example
{
int myFunc();
}
.cpp
namespace Example
{
int hiddenVar;
int myFunc()
{
.. do something with hiddenVar
return someValue;
}
}
My problem is that I need to define a template function that requires access to this hidden variable. Unfortunately since the body of the template function must be defined in the header file it wont have access to the variable hidden in the .cpp.
.h
namespace Example
{
template< typename T >
void myFunc( const T& myT )
{
.. do something with hiddenVar // doesnt know what hiddenVar is
}
}
.cpp
namespace Example
{
int hiddenVar;
}
Is there anyway to have a variable hidden within a namespace while giving a template function in the header access to it?
Upvotes: 2
Views: 871
Reputation: 7399
Put it in a nested namespace called 'Details' and stop worrying.
'Hiding' a variable using namespaces and private etc are not security-constructs, but there to facilitate better code.
Upvotes: 0
Reputation: 11028
You cannot do this directly, but you can use a function. Since hiddenVar
does not depend on the template parameters, you can do this:
.h
namespace Example
{
void Function(); // Use the right function prototype here, of course,
// as long as it does not depend on T
template<typename T>
void myFunc(const T& myT)
{
//...
Function();
//...
}
}
.cpp
namespace Example
{
int hiddenVar;
void Function()
{
// Do something with hiddenVar
}
}
If your use of hiddenVar
depends on T
, of course, you are out of luck.
Upvotes: 0
Reputation: 1277
.h:
namespace Example
{
int * get_hiddenVar();
template< typename T >
void myFunc( const T& myT )
{
int * hiddenVarPtr = get_hiddenVar();
.. do something with *hiddenVarPtr
}
}
.cpp
namespace Example
{
int hiddenVar=0;
int * get_hiddenVar()
{
return &hiddenVar;
}
}
Upvotes: 1