Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ local function within a namespace

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.

like image 386
Tom Avatar asked Apr 17 '26 12:04

Tom


1 Answers

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 () {
        ... 
    }

}
like image 146
Christophe Avatar answered Apr 19 '26 02:04

Christophe