Coming from ADA there is one thing I really miss in C++ and that is the ability to use nested or local functions. In ADA I could do this for example:
procedure TotalSum ()
is
function Sum (a : Float; b : Float) return Float;
is
begin
return a + b;
end Sum;
x : Float := 1.0;
y : Float := 1.0;
z : Float := 1.0;
sum : Float;
begin
sum := Sum(x,y);
sum := Sum(sum,z);
end TotalSum;
The advantage of this is that I can limit the scope of functions that are only used locally. For classes I got used to the fact that I can declare a function private in order to limit the scope (which limits the scope to some extend). But now I'm implementing a function library in a namespace instead of a class and I've not been able to find a nice solution to limit the scope of my local functions.
Is there a best practice to accomplish the above in a C++ namespace.
You can perfectly define local functions using lambda functions:
int TotalSum () {
auto Sum = [](float a, float b) -> float {
return a + b;
};
float x= 1.0;
float y= 1.0;
float z= 1.0;
float sum = Sum(x,y);
sum = Sum(sum,z);
return sum;
}
Another approach to keep a function completely local to an implementation could be to use anonymous namespace. The elements defined in an anonymous namespace are local to the translation unit (i.e. in one cpp file only):
namespace mylib {
namespace { // nested anonymous namespace - visible only in this cpp
float Sum (float a, float b) {
return a + b;
}
};
int TotalSum () {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With