Binding a const function reference to a lambdaWhat is a lambda (function)?What are the differences between a pointer variable and a reference variable in C++?Why are Python lambdas useful?What is the difference between const int*, const int * const, and int const *?How come a non-const reference cannot bind to a temporary object?C++0x lambda capture by value always const?Returning unique_ptr from functionsWhat is a lambda expression in C++11?Returning temporary object and binding to const referenceReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations

Did the Ottoman empire suppress the printing press?

Why did Harry Potter get a bedroom?

"was fiction" vs "were fictions"

Found and corrected a mistake on someone's else paper -- praxis?

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

Distinguish the explanations of Galadriel's test in LotR

How do we handle pauses in a dialogue?

Swapping "Good" and "Bad"

Is there a minimum field size for peah to apply?

Can I play a mimic PC?

Why does the Antonov AN-225 not have any winglets?

What is the right approach to quit a job during probation period for a competing offer?

What would +1/+2/+3 items be called in game?

GDPR rights when subject dies; does family inherit subject rights?

How do native German speakers usually express skepticism (using even) about a premise?

WTB Horizon 47c - small crack in the middle of the tire

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

Why is Nibbana referred to as "The destination and the path leading to the destination"?

Under what hypotheses do all bounded sets have "area"?

How can I effectively communicate to recruiters that a phone call is not possible?

LED glows slightly during soldering

Is this a reference to the film Alien in the novel 2010 Odyssey Two?

What attributes and how big would a sea creature(s) need to be able to tow a ship?

Misrepresented my work history



Binding a const function reference to a lambda


What is a lambda (function)?What are the differences between a pointer variable and a reference variable in C++?Why are Python lambdas useful?What is the difference between const int*, const int * const, and int const *?How come a non-const reference cannot bind to a temporary object?C++0x lambda capture by value always const?Returning unique_ptr from functionsWhat is a lambda expression in C++11?Returning temporary object and binding to const referenceReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








16















This code



int(&foo)(int, int) = [](int a, int b) return a + b; ;


doesn't compile since apparently a non-const reference can't be initialized with a temporary. Where do I put the const?










share|improve this question
























  • Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

    – Narase
    Jul 1 at 4:41











  • It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

    – cpplearner
    Jul 1 at 4:43






  • 1





    Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

    – Yang
    Jul 1 at 4:45












  • It doesn't need to be, I'm just curious how/if this can be done.

    – Artikash
    Jul 1 at 4:58

















16















This code



int(&foo)(int, int) = [](int a, int b) return a + b; ;


doesn't compile since apparently a non-const reference can't be initialized with a temporary. Where do I put the const?










share|improve this question
























  • Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

    – Narase
    Jul 1 at 4:41











  • It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

    – cpplearner
    Jul 1 at 4:43






  • 1





    Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

    – Yang
    Jul 1 at 4:45












  • It doesn't need to be, I'm just curious how/if this can be done.

    – Artikash
    Jul 1 at 4:58













16












16








16


3






This code



int(&foo)(int, int) = [](int a, int b) return a + b; ;


doesn't compile since apparently a non-const reference can't be initialized with a temporary. Where do I put the const?










share|improve this question
















This code



int(&foo)(int, int) = [](int a, int b) return a + b; ;


doesn't compile since apparently a non-const reference can't be initialized with a temporary. Where do I put the const?







c++ c++11 lambda






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 1 at 8:21









StoryTeller

114k18 gold badges245 silver badges311 bronze badges




114k18 gold badges245 silver badges311 bronze badges










asked Jul 1 at 4:33









ArtikashArtikash

3153 silver badges11 bronze badges




3153 silver badges11 bronze badges












  • Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

    – Narase
    Jul 1 at 4:41











  • It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

    – cpplearner
    Jul 1 at 4:43






  • 1





    Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

    – Yang
    Jul 1 at 4:45












  • It doesn't need to be, I'm just curious how/if this can be done.

    – Artikash
    Jul 1 at 4:58

















  • Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

    – Narase
    Jul 1 at 4:41











  • It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

    – cpplearner
    Jul 1 at 4:43






  • 1





    Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

    – Yang
    Jul 1 at 4:45












  • It doesn't need to be, I'm just curious how/if this can be done.

    – Artikash
    Jul 1 at 4:58
















Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

– Narase
Jul 1 at 4:41





Why does it need to be a const ref? By making a copy the compiler will make use of the move semantics

– Narase
Jul 1 at 4:41













It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

– cpplearner
Jul 1 at 4:43





It doesn't compile because a lambda does not have conversion to reference. The compiler error is misleading.

– cpplearner
Jul 1 at 4:43




1




1





Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

– Yang
Jul 1 at 4:45






Why not just use auto foo = [](int a, int b) return a + b; ;? C++ will move instead of copy the temporary.

– Yang
Jul 1 at 4:45














It doesn't need to be, I'm just curious how/if this can be done.

– Artikash
Jul 1 at 4:58





It doesn't need to be, I'm just curious how/if this can be done.

– Artikash
Jul 1 at 4:58












2 Answers
2






active

oldest

votes


















24














As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.



int(&foo)(int, int) = *[](int a, int b) return a + b; ;


Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator*, but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.



Here it is live.






share|improve this answer






























    11














    A lambda can only be converted to a function pointer if it does not capture.




    The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator




    [Lambda Functions][1]


    I changed your code as below and it worked.



    int (*foo)(int, int)= [] (int a, int b) return a + b; ;
    int main()

    cout << "Res:: " << foo(10,20);
    return 0;



    I just make it function pointer.



    Alternatively,



    auto foo = [](int a, int b) return a + b; ; 


    is also a good choice.



    I hope it helps!






    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',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      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%2f56830028%2fbinding-a-const-function-reference-to-a-lambda%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      24














      As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.



      int(&foo)(int, int) = *[](int a, int b) return a + b; ;


      Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator*, but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.



      Here it is live.






      share|improve this answer



























        24














        As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.



        int(&foo)(int, int) = *[](int a, int b) return a + b; ;


        Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator*, but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.



        Here it is live.






        share|improve this answer

























          24












          24








          24







          As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.



          int(&foo)(int, int) = *[](int a, int b) return a + b; ;


          Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator*, but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.



          Here it is live.






          share|improve this answer













          As mentioned already, a capture-less lambda is convertible to a function pointer. So if you want to bind that static function to a reference, you need to dereference the pointer.



          int(&foo)(int, int) = *[](int a, int b) return a + b; ;


          Applying * to the lambda causes a bunch of machinery to kick in. Since the lambda doesn't overload operator*, but does implement a conversion to a pointer type, that conversion happens. Afterwards * is applied to the returned pointer and that yields a function lvalue. That lvalue can then bind to the reference.



          Here it is live.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jul 1 at 5:26









          StoryTellerStoryTeller

          114k18 gold badges245 silver badges311 bronze badges




          114k18 gold badges245 silver badges311 bronze badges























              11














              A lambda can only be converted to a function pointer if it does not capture.




              The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator




              [Lambda Functions][1]


              I changed your code as below and it worked.



              int (*foo)(int, int)= [] (int a, int b) return a + b; ;
              int main()

              cout << "Res:: " << foo(10,20);
              return 0;



              I just make it function pointer.



              Alternatively,



              auto foo = [](int a, int b) return a + b; ; 


              is also a good choice.



              I hope it helps!






              share|improve this answer



























                11














                A lambda can only be converted to a function pointer if it does not capture.




                The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator




                [Lambda Functions][1]


                I changed your code as below and it worked.



                int (*foo)(int, int)= [] (int a, int b) return a + b; ;
                int main()

                cout << "Res:: " << foo(10,20);
                return 0;



                I just make it function pointer.



                Alternatively,



                auto foo = [](int a, int b) return a + b; ; 


                is also a good choice.



                I hope it helps!






                share|improve this answer

























                  11












                  11








                  11







                  A lambda can only be converted to a function pointer if it does not capture.




                  The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator




                  [Lambda Functions][1]


                  I changed your code as below and it worked.



                  int (*foo)(int, int)= [] (int a, int b) return a + b; ;
                  int main()

                  cout << "Res:: " << foo(10,20);
                  return 0;



                  I just make it function pointer.



                  Alternatively,



                  auto foo = [](int a, int b) return a + b; ; 


                  is also a good choice.



                  I hope it helps!






                  share|improve this answer













                  A lambda can only be converted to a function pointer if it does not capture.




                  The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator




                  [Lambda Functions][1]


                  I changed your code as below and it worked.



                  int (*foo)(int, int)= [] (int a, int b) return a + b; ;
                  int main()

                  cout << "Res:: " << foo(10,20);
                  return 0;



                  I just make it function pointer.



                  Alternatively,



                  auto foo = [](int a, int b) return a + b; ; 


                  is also a good choice.



                  I hope it helps!







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 1 at 5:06









                  Abhishek SinhaAbhishek Sinha

                  3811 silver badge6 bronze badges




                  3811 silver badge6 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56830028%2fbinding-a-const-function-reference-to-a-lambda%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                      Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                      Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?