Hello,
I was trying to experiment with some functional programming on a small-scale project and was wondering if my current namespace convention was good practice.
Basically, I declare a set of functions under a namespace in a header file:
1 2 3 4 5 6
namespace listOfFunctions {
void initialize();
void cleanup();
int foo();
int bar();
}
I then define them in the corresponding source file. Now in some cases, there are some static variables that these functions should share. So in the source file, I put these variables in an anonymous namespace so that they can't be modified elsewhere.
namespace {
int var1;
int var2;
}
namespace listOfFunctions {
void initialize() {
//initialize var1 & var 2
}
void cleanup() {
//free var1 & var 2 resources
}
int foo() {
//use var1 & var 2
}
int bar() {
//use var1 & var 2
}
}
My question is, since I want to avoid using classes and singletons, I thought this would be a safer way to have a set of global functions, but is it good style/convention?
I guess you can program functional style in C++ if you try hard enough (I did try recently, and it worked semi-well for small things) - but why bother?
EDIT: Looking at your pseudocode, you don't actually use functional style at all. So what were you actually going to ask?
That's sort of what namespaces are for, to provide a scope for declarations. You do realise you can nest namespaces too, right?
But don't go for fine grain control, a namespace per library is enough, and that namespace can be further subdivided. But always consider how a user might call your code. Aim for concise simplicity. STL is a good reference example.
int main()
{
auto tree = parser::parse( "whatever.txt" ) ; // parser::version_1::parse today
// may be parser::version_2::parse tomorrow
auto tree2 = parser::version_1::parse( "whatever.txt" ) ; // always version_1
}
Note: Use C++11 inline namespaces instead, when they become widely supported.
I am not able to understand any thing .... may be because i am too tierd .. and need some sleep .. but request you all there to be more simple .. so that i can understand it .
thanks in advance
xx