Hi!
I have some functions that can be grouped together, but don't belong to some object / entity and therefore can't be treated as methods.
So, basically in this situation I would create a new namespace and put the definitions in a header
file, the implementation in cpp
file. Also (if needed) I would create an anonymous namespace in that cpp
file and put all additional functions that don't have to be exposed / included to my namespace's interface there.
See the code below (probably not the best example and could be done better with another program architecture, but I just can't think of a better sample...)
Sample code (header
)
namespace algorithm {
void HandleCollision(Object* object1, Object* object2);
}
Sample code (cpp
)
#include "header"
// Anonymous namespace that wraps
// routines that are used inside 'algorithm' methods
// but don't have to be exposed
namespace {
void RefractObject(Object* object1) {
// Do something with that object
// (...)
}
}
namespace algorithm {
void HandleCollision(Object* object1, Object* object2) {
if (...) RefractObject(object1);
}
}
So far so good. I guess this is a good way to manage my code, but I don't know what should I do if I have some template-based functions and want to do basically the same.
If I'm using templates, I have to put all my code in the header
file. Ok, but how should I conceal some implementation details then?
Like, I want to hide RefractObject
function from my interface, but I can't simply remove it's declaration (just because I have all my code in a header
file)...
The only approach I came up with was something like:
Sample code (header
)
namespace algorithm {
// Is still exposed as a part of interface!
namespace impl {
template <typename T>
void RefractObject(T* object1) {
// Do something with that object
// (...)
}
}
template <typename T, typename Y>
void HandleCollision(T* object1, Y* object2) {
impl::RefractObject(object1);
// Another stuff
}
}
Any ideas how to make this better in terms of code designing?