Why would one write a C++ lambda with a name so it can be called from somewhere?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
5
down vote

favorite












Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?







share|improve this question




















  • If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
    – hellow
    Aug 10 at 7:20














up vote
5
down vote

favorite












Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?







share|improve this question




















  • If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
    – hellow
    Aug 10 at 7:20












up vote
5
down vote

favorite









up vote
5
down vote

favorite











Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?







share|improve this question












Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?









share|improve this question











share|improve this question




share|improve this question










asked Aug 9 at 6:16









user9639921

817




817











  • If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
    – hellow
    Aug 10 at 7:20
















  • If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
    – hellow
    Aug 10 at 7:20















If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
– hellow
Aug 10 at 7:20




If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved to your satisfaction, and it gives the person that helps you credit for the assist. See here for a full explanation.
– hellow
Aug 10 at 7:20












4 Answers
4






active

oldest

votes

















up vote
1
down vote



accepted










I see three things to consider when choosing between a named lamdba and a free function:



  1. Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).

  2. Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).


  3. Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure



    • is a bit confusing in a header file (though this is debatable, of course).


    • requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.







share|improve this answer



























    up vote
    3
    down vote













    One use of this is to have a function access the enclosing scope.



    In C++, we don't have nested functions as we do in some other languages.
    Having a named lambda solves this problem.
    An example:



    #include <iostream>

    int main ()

    int x;

    auto fun = [&] (int y)
    return x + y;
    ;

    std::cin >> x;

    int t;
    std::cin >> t;
    std::cout << fun (fun (t));
    return 0;



    Here, the function fun is basically a nested function in main, able to access its local variables.
    We can format it so that it resembles a regular function, and use it more than once.






    share|improve this answer






















    • But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
      – Gem Taylor
      Aug 9 at 14:22











    • Can I write it as an inline function then if it needs surrounding variable?
      – user9639921
      Aug 10 at 4:48










    • @GemTaylor I've made an edit to incorporate your notions.
      – Gassa
      Aug 10 at 7:46










    • @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
      – Gassa
      Aug 10 at 7:47










    • @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
      – Gem Taylor
      Aug 10 at 9:20

















    up vote
    1
    down vote













    This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.



    But beside of that, there is no difference.






    share|improve this answer





























      up vote
      0
      down vote













      A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:



      std::string key;
      std::map<std::string, int> v;


      one can write the following:



      std::find_if( v.begin(), v.end(), (auto const& elem) return elem.first == key; );


      but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:



      auto matches_key = (auto const& elem) return elem.first == key; ;

      std::find_if( v.begin(), v.end(), matches_key );


      it is clearer that we do want the equality comparison and the readability is improved.






      share|improve this answer




















        Your Answer





        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: false,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













         

        draft saved


        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51760019%2fwhy-would-one-write-a-c-lambda-with-a-name-so-it-can-be-called-from-somewhere%23new-answer', 'question_page');

        );

        Post as a guest






























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        1
        down vote



        accepted










        I see three things to consider when choosing between a named lamdba and a free function:



        1. Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).

        2. Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).


        3. Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure



          • is a bit confusing in a header file (though this is debatable, of course).


          • requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.







        share|improve this answer
























          up vote
          1
          down vote



          accepted










          I see three things to consider when choosing between a named lamdba and a free function:



          1. Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).

          2. Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).


          3. Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure



            • is a bit confusing in a header file (though this is debatable, of course).


            • requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.







          share|improve this answer






















            up vote
            1
            down vote



            accepted







            up vote
            1
            down vote



            accepted






            I see three things to consider when choosing between a named lamdba and a free function:



            1. Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).

            2. Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).


            3. Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure



              • is a bit confusing in a header file (though this is debatable, of course).


              • requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.







            share|improve this answer












            I see three things to consider when choosing between a named lamdba and a free function:



            1. Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).

            2. Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).


            3. Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure



              • is a bit confusing in a header file (though this is debatable, of course).


              • requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 9 at 6:58









            lubgr

            5,6411238




            5,6411238






















                up vote
                3
                down vote













                One use of this is to have a function access the enclosing scope.



                In C++, we don't have nested functions as we do in some other languages.
                Having a named lambda solves this problem.
                An example:



                #include <iostream>

                int main ()

                int x;

                auto fun = [&] (int y)
                return x + y;
                ;

                std::cin >> x;

                int t;
                std::cin >> t;
                std::cout << fun (fun (t));
                return 0;



                Here, the function fun is basically a nested function in main, able to access its local variables.
                We can format it so that it resembles a regular function, and use it more than once.






                share|improve this answer






















                • But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                  – Gem Taylor
                  Aug 9 at 14:22











                • Can I write it as an inline function then if it needs surrounding variable?
                  – user9639921
                  Aug 10 at 4:48










                • @GemTaylor I've made an edit to incorporate your notions.
                  – Gassa
                  Aug 10 at 7:46










                • @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                  – Gassa
                  Aug 10 at 7:47










                • @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                  – Gem Taylor
                  Aug 10 at 9:20














                up vote
                3
                down vote













                One use of this is to have a function access the enclosing scope.



                In C++, we don't have nested functions as we do in some other languages.
                Having a named lambda solves this problem.
                An example:



                #include <iostream>

                int main ()

                int x;

                auto fun = [&] (int y)
                return x + y;
                ;

                std::cin >> x;

                int t;
                std::cin >> t;
                std::cout << fun (fun (t));
                return 0;



                Here, the function fun is basically a nested function in main, able to access its local variables.
                We can format it so that it resembles a regular function, and use it more than once.






                share|improve this answer






















                • But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                  – Gem Taylor
                  Aug 9 at 14:22











                • Can I write it as an inline function then if it needs surrounding variable?
                  – user9639921
                  Aug 10 at 4:48










                • @GemTaylor I've made an edit to incorporate your notions.
                  – Gassa
                  Aug 10 at 7:46










                • @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                  – Gassa
                  Aug 10 at 7:47










                • @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                  – Gem Taylor
                  Aug 10 at 9:20












                up vote
                3
                down vote










                up vote
                3
                down vote









                One use of this is to have a function access the enclosing scope.



                In C++, we don't have nested functions as we do in some other languages.
                Having a named lambda solves this problem.
                An example:



                #include <iostream>

                int main ()

                int x;

                auto fun = [&] (int y)
                return x + y;
                ;

                std::cin >> x;

                int t;
                std::cin >> t;
                std::cout << fun (fun (t));
                return 0;



                Here, the function fun is basically a nested function in main, able to access its local variables.
                We can format it so that it resembles a regular function, and use it more than once.






                share|improve this answer














                One use of this is to have a function access the enclosing scope.



                In C++, we don't have nested functions as we do in some other languages.
                Having a named lambda solves this problem.
                An example:



                #include <iostream>

                int main ()

                int x;

                auto fun = [&] (int y)
                return x + y;
                ;

                std::cin >> x;

                int t;
                std::cin >> t;
                std::cout << fun (fun (t));
                return 0;



                Here, the function fun is basically a nested function in main, able to access its local variables.
                We can format it so that it resembles a regular function, and use it more than once.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Aug 10 at 7:45

























                answered Aug 9 at 6:23









                Gassa

                6,57731938




                6,57731938











                • But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                  – Gem Taylor
                  Aug 9 at 14:22











                • Can I write it as an inline function then if it needs surrounding variable?
                  – user9639921
                  Aug 10 at 4:48










                • @GemTaylor I've made an edit to incorporate your notions.
                  – Gassa
                  Aug 10 at 7:46










                • @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                  – Gassa
                  Aug 10 at 7:47










                • @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                  – Gem Taylor
                  Aug 10 at 9:20
















                • But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                  – Gem Taylor
                  Aug 9 at 14:22











                • Can I write it as an inline function then if it needs surrounding variable?
                  – user9639921
                  Aug 10 at 4:48










                • @GemTaylor I've made an edit to incorporate your notions.
                  – Gassa
                  Aug 10 at 7:46










                • @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                  – Gassa
                  Aug 10 at 7:47










                • @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                  – Gem Taylor
                  Aug 10 at 9:20















                But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                – Gem Taylor
                Aug 9 at 14:22





                But in this case, as you only use the lambda one time, it could have been written and executed inline with the std::cout <<. The main advantage of not doing so is readability if the lambda is more than 1 line, and perhaps visible locality.
                – Gem Taylor
                Aug 9 at 14:22













                Can I write it as an inline function then if it needs surrounding variable?
                – user9639921
                Aug 10 at 4:48




                Can I write it as an inline function then if it needs surrounding variable?
                – user9639921
                Aug 10 at 4:48












                @GemTaylor I've made an edit to incorporate your notions.
                – Gassa
                Aug 10 at 7:46




                @GemTaylor I've made an edit to incorporate your notions.
                – Gassa
                Aug 10 at 7:46












                @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                – Gassa
                Aug 10 at 7:47




                @user9639921 There are other ways to achieve similarity to nested functions. Here is a relevant question.
                – Gassa
                Aug 10 at 7:47












                @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                – Gem Taylor
                Aug 10 at 9:20




                @Gassa Yes, you can use the static member of a local class. That is what we used to have to do pre-'11. lambdas are better than that, and the compiler can optimise away the "function pointer" quite easily. Unsurprisingly, the reference implementation of lambdas is exactly this.
                – Gem Taylor
                Aug 10 at 9:20










                up vote
                1
                down vote













                This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.



                But beside of that, there is no difference.






                share|improve this answer


























                  up vote
                  1
                  down vote













                  This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.



                  But beside of that, there is no difference.






                  share|improve this answer
























                    up vote
                    1
                    down vote










                    up vote
                    1
                    down vote









                    This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.



                    But beside of that, there is no difference.






                    share|improve this answer














                    This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.



                    But beside of that, there is no difference.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Aug 9 at 6:39

























                    answered Aug 9 at 6:18









                    hellow

                    2,3811733




                    2,3811733




















                        up vote
                        0
                        down vote













                        A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:



                        std::string key;
                        std::map<std::string, int> v;


                        one can write the following:



                        std::find_if( v.begin(), v.end(), (auto const& elem) return elem.first == key; );


                        but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:



                        auto matches_key = (auto const& elem) return elem.first == key; ;

                        std::find_if( v.begin(), v.end(), matches_key );


                        it is clearer that we do want the equality comparison and the readability is improved.






                        share|improve this answer
























                          up vote
                          0
                          down vote













                          A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:



                          std::string key;
                          std::map<std::string, int> v;


                          one can write the following:



                          std::find_if( v.begin(), v.end(), (auto const& elem) return elem.first == key; );


                          but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:



                          auto matches_key = (auto const& elem) return elem.first == key; ;

                          std::find_if( v.begin(), v.end(), matches_key );


                          it is clearer that we do want the equality comparison and the readability is improved.






                          share|improve this answer






















                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:



                            std::string key;
                            std::map<std::string, int> v;


                            one can write the following:



                            std::find_if( v.begin(), v.end(), (auto const& elem) return elem.first == key; );


                            but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:



                            auto matches_key = (auto const& elem) return elem.first == key; ;

                            std::find_if( v.begin(), v.end(), matches_key );


                            it is clearer that we do want the equality comparison and the readability is improved.






                            share|improve this answer












                            A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:



                            std::string key;
                            std::map<std::string, int> v;


                            one can write the following:



                            std::find_if( v.begin(), v.end(), (auto const& elem) return elem.first == key; );


                            but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:



                            auto matches_key = (auto const& elem) return elem.first == key; ;

                            std::find_if( v.begin(), v.end(), matches_key );


                            it is clearer that we do want the equality comparison and the readability is improved.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 12 at 20:02









                            Thomas

                            3,1222919




                            3,1222919



























                                 

                                draft saved


                                draft discarded















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51760019%2fwhy-would-one-write-a-c-lambda-with-a-name-so-it-can-be-called-from-somewhere%23new-answer', 'question_page');

                                );

                                Post as a guest













































































                                Comments

                                Popular posts from this blog

                                What does second last employer means? [closed]

                                List of Gilmore Girls characters

                                Confectionery