Deducing Lambda Capture TypesUnderstanding C++0x lambda capturesWhat is a lambda expression in C++11?Lambda capturing constexpr objectHow is the this pointer captured?Lambda capture reference by copy and decltypedecltype(auto) deduced return type from lambda captureHow function template type deduction works when parameter type is const lvalue reference vs non-const lvalue refernce in c++11What is decltype(x) inside a lambda supposed to return when x is captured by reference?Deduced conflicting types for universal reference and pointer to memberWhy does [=] have a lambda capture?

Installed software from source, how to say yum not to install it from package?

Is it advisable to inform the CEO about his brother accessing his office?

Why will we fail creating a self sustaining off world colony?

Did the Russian Empire have a claim to Sweden? Was there ever a time where they could have pursued it?

Should Catholics in a state of grace call themselves sinners?

Can I submit a paper to two or more journals at the same time?

Why was Pan Am Flight 103 flying over Lockerbie?

Can dual citizens open crypto exchange accounts where U.S. citizens are prohibited?

Does "boire un jus" tend to mean "coffee" or "juice of fruit"?

Is it possible to alias a column based on the result of a select+where?

What is the meaning of 'shout over' in a sentence exactly?

How far can gerrymandering go?

Why do movie directors use brown tint on Mexico cities?

What prevents a US state from colonizing a smaller state?

English idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)

Delete all files from a folder using a bat that match a certain pattern in Windows 10

What was the first science fiction or fantasy multiple choice book?

A* pathfinding algorithm too slow

Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?

Why doesn't SpaceX land boosters in Africa?

Deducing Lambda Capture Types

Could all three Gorgons turn people to stone, or just Medusa?

What are the children of two Muggle-borns called?

A quine of sorts



Deducing Lambda Capture Types


Understanding C++0x lambda capturesWhat is a lambda expression in C++11?Lambda capturing constexpr objectHow is the this pointer captured?Lambda capture reference by copy and decltypedecltype(auto) deduced return type from lambda captureHow function template type deduction works when parameter type is const lvalue reference vs non-const lvalue refernce in c++11What is decltype(x) inside a lambda supposed to return when x is captured by reference?Deduced conflicting types for universal reference and pointer to memberWhy does [=] have a lambda capture?













8















I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.

For example:



const int x = 0;
auto foo = [x]
// x is const int
;


This behavior is mentioned in § 8.1.5.2 in the draft for C++17:




For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The
declaration order of these members is unspecified. The type of such a data member is the referenced type
if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity
is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an
anonymous union shall not be captured by copy.




I would expect that deducing type of captured variables will be the same as deducing auto.

Is there a good reason for having different type-deduction rules for captured types?










share|improve this question


























    8















    I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.

    For example:



    const int x = 0;
    auto foo = [x]
    // x is const int
    ;


    This behavior is mentioned in § 8.1.5.2 in the draft for C++17:




    For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The
    declaration order of these members is unspecified. The type of such a data member is the referenced type
    if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity
    is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an
    anonymous union shall not be captured by copy.




    I would expect that deducing type of captured variables will be the same as deducing auto.

    Is there a good reason for having different type-deduction rules for captured types?










    share|improve this question
























      8












      8








      8


      1






      I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.

      For example:



      const int x = 0;
      auto foo = [x]
      // x is const int
      ;


      This behavior is mentioned in § 8.1.5.2 in the draft for C++17:




      For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The
      declaration order of these members is unspecified. The type of such a data member is the referenced type
      if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity
      is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an
      anonymous union shall not be captured by copy.




      I would expect that deducing type of captured variables will be the same as deducing auto.

      Is there a good reason for having different type-deduction rules for captured types?










      share|improve this question














      I've recently found that capturing a const object by value in a lambda, implies that the variable inside the labmda's body (i.e. the lambda's data member) is also const.

      For example:



      const int x = 0;
      auto foo = [x]
      // x is const int
      ;


      This behavior is mentioned in § 8.1.5.2 in the draft for C++17:




      For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The
      declaration order of these members is unspecified. The type of such a data member is the referenced type
      if the entity is a reference to an object, an lvalue reference to the referenced function type if the entity
      is a reference to a function, or the type of the corresponding captured entity otherwise. A member of an
      anonymous union shall not be captured by copy.




      I would expect that deducing type of captured variables will be the same as deducing auto.

      Is there a good reason for having different type-deduction rules for captured types?







      c++ c++11






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      Mr. AndersonMr. Anderson

      5925 silver badges17 bronze badges




      5925 silver badges17 bronze badges




















          3 Answers
          3






          active

          oldest

          votes


















          5














          In your example, it would not be possible to modify x since the lambda is not mutable, which makes the function call operator const. But even if the lambda is mutable, it's true that the quoted passage makes the type of x in the lambda const int.



          If I remember correctly, this was a deliberate design decision in C++11 to make the use of x within the lambda behave similarly to the use of x in the enclosing scope. That is,



          void foo(int&);
          void foo(const int&);
          const int x = 0;
          foo(x); // calls foo(const int&)
          auto foo = [x]() mutable
          foo(x); // also calls foo(const int&)
          ;


          This helps to avoid bugs when, e.g., some code is rewritten from having an explicit loop to calling a standard library algorithm with a lambda.



          If I'm wrong about this recollection, hopefully someone with the right answer will step in and write their own answer.






          share|improve this answer






























            1














            Not an answer to the reasoning; There is already a comprehensive answer here.



            For those who want to know how to capture a non-const copy of a const variable, you can use a capture with an initialiser:



            const int x = 0;
            auto foo = [x = x]() mutable
            // x is non-const
            ;


            That requires C++14 though. A C++11 compatible solution is to make the copy outside the lambda:



            const int x = 0;
            int copy = x;
            auto foo = [x]() mutable
            // copy is non-const
            ;





            share|improve this answer




















            • 1





              Nitpicking, but it would require the C++14 tag

              – LWimsey
              7 hours ago











            • @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

              – eerorika
              7 hours ago











            • Did you mean auto foo = [copy]...?

              – Paul Sanders
              4 hours ago


















            0














            The reason is that operator() in lambda is const by default.



            int main()

            const int x = 0;
            auto foo = [x](); // main::$_0::operator()() const
            foo();



            So you have to use mutable lambda:



            int main()

            const int x = 0;
            auto foo = [x=x](); // main::$_0::operator()()
            foo();






            share|improve this answer




















            • 1





              mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

              – LWimsey
              7 hours ago













            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%2f56811624%2fdeducing-lambda-capture-types%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            In your example, it would not be possible to modify x since the lambda is not mutable, which makes the function call operator const. But even if the lambda is mutable, it's true that the quoted passage makes the type of x in the lambda const int.



            If I remember correctly, this was a deliberate design decision in C++11 to make the use of x within the lambda behave similarly to the use of x in the enclosing scope. That is,



            void foo(int&);
            void foo(const int&);
            const int x = 0;
            foo(x); // calls foo(const int&)
            auto foo = [x]() mutable
            foo(x); // also calls foo(const int&)
            ;


            This helps to avoid bugs when, e.g., some code is rewritten from having an explicit loop to calling a standard library algorithm with a lambda.



            If I'm wrong about this recollection, hopefully someone with the right answer will step in and write their own answer.






            share|improve this answer



























              5














              In your example, it would not be possible to modify x since the lambda is not mutable, which makes the function call operator const. But even if the lambda is mutable, it's true that the quoted passage makes the type of x in the lambda const int.



              If I remember correctly, this was a deliberate design decision in C++11 to make the use of x within the lambda behave similarly to the use of x in the enclosing scope. That is,



              void foo(int&);
              void foo(const int&);
              const int x = 0;
              foo(x); // calls foo(const int&)
              auto foo = [x]() mutable
              foo(x); // also calls foo(const int&)
              ;


              This helps to avoid bugs when, e.g., some code is rewritten from having an explicit loop to calling a standard library algorithm with a lambda.



              If I'm wrong about this recollection, hopefully someone with the right answer will step in and write their own answer.






              share|improve this answer

























                5












                5








                5







                In your example, it would not be possible to modify x since the lambda is not mutable, which makes the function call operator const. But even if the lambda is mutable, it's true that the quoted passage makes the type of x in the lambda const int.



                If I remember correctly, this was a deliberate design decision in C++11 to make the use of x within the lambda behave similarly to the use of x in the enclosing scope. That is,



                void foo(int&);
                void foo(const int&);
                const int x = 0;
                foo(x); // calls foo(const int&)
                auto foo = [x]() mutable
                foo(x); // also calls foo(const int&)
                ;


                This helps to avoid bugs when, e.g., some code is rewritten from having an explicit loop to calling a standard library algorithm with a lambda.



                If I'm wrong about this recollection, hopefully someone with the right answer will step in and write their own answer.






                share|improve this answer













                In your example, it would not be possible to modify x since the lambda is not mutable, which makes the function call operator const. But even if the lambda is mutable, it's true that the quoted passage makes the type of x in the lambda const int.



                If I remember correctly, this was a deliberate design decision in C++11 to make the use of x within the lambda behave similarly to the use of x in the enclosing scope. That is,



                void foo(int&);
                void foo(const int&);
                const int x = 0;
                foo(x); // calls foo(const int&)
                auto foo = [x]() mutable
                foo(x); // also calls foo(const int&)
                ;


                This helps to avoid bugs when, e.g., some code is rewritten from having an explicit loop to calling a standard library algorithm with a lambda.



                If I'm wrong about this recollection, hopefully someone with the right answer will step in and write their own answer.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 8 hours ago









                BrianBrian

                69.3k7 gold badges101 silver badges197 bronze badges




                69.3k7 gold badges101 silver badges197 bronze badges





















                    1














                    Not an answer to the reasoning; There is already a comprehensive answer here.



                    For those who want to know how to capture a non-const copy of a const variable, you can use a capture with an initialiser:



                    const int x = 0;
                    auto foo = [x = x]() mutable
                    // x is non-const
                    ;


                    That requires C++14 though. A C++11 compatible solution is to make the copy outside the lambda:



                    const int x = 0;
                    int copy = x;
                    auto foo = [x]() mutable
                    // copy is non-const
                    ;





                    share|improve this answer




















                    • 1





                      Nitpicking, but it would require the C++14 tag

                      – LWimsey
                      7 hours ago











                    • @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                      – eerorika
                      7 hours ago











                    • Did you mean auto foo = [copy]...?

                      – Paul Sanders
                      4 hours ago















                    1














                    Not an answer to the reasoning; There is already a comprehensive answer here.



                    For those who want to know how to capture a non-const copy of a const variable, you can use a capture with an initialiser:



                    const int x = 0;
                    auto foo = [x = x]() mutable
                    // x is non-const
                    ;


                    That requires C++14 though. A C++11 compatible solution is to make the copy outside the lambda:



                    const int x = 0;
                    int copy = x;
                    auto foo = [x]() mutable
                    // copy is non-const
                    ;





                    share|improve this answer




















                    • 1





                      Nitpicking, but it would require the C++14 tag

                      – LWimsey
                      7 hours ago











                    • @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                      – eerorika
                      7 hours ago











                    • Did you mean auto foo = [copy]...?

                      – Paul Sanders
                      4 hours ago













                    1












                    1








                    1







                    Not an answer to the reasoning; There is already a comprehensive answer here.



                    For those who want to know how to capture a non-const copy of a const variable, you can use a capture with an initialiser:



                    const int x = 0;
                    auto foo = [x = x]() mutable
                    // x is non-const
                    ;


                    That requires C++14 though. A C++11 compatible solution is to make the copy outside the lambda:



                    const int x = 0;
                    int copy = x;
                    auto foo = [x]() mutable
                    // copy is non-const
                    ;





                    share|improve this answer















                    Not an answer to the reasoning; There is already a comprehensive answer here.



                    For those who want to know how to capture a non-const copy of a const variable, you can use a capture with an initialiser:



                    const int x = 0;
                    auto foo = [x = x]() mutable
                    // x is non-const
                    ;


                    That requires C++14 though. A C++11 compatible solution is to make the copy outside the lambda:



                    const int x = 0;
                    int copy = x;
                    auto foo = [x]() mutable
                    // copy is non-const
                    ;






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 7 hours ago

























                    answered 8 hours ago









                    eerorikaeerorika

                    97k6 gold badges77 silver badges145 bronze badges




                    97k6 gold badges77 silver badges145 bronze badges







                    • 1





                      Nitpicking, but it would require the C++14 tag

                      – LWimsey
                      7 hours ago











                    • @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                      – eerorika
                      7 hours ago











                    • Did you mean auto foo = [copy]...?

                      – Paul Sanders
                      4 hours ago












                    • 1





                      Nitpicking, but it would require the C++14 tag

                      – LWimsey
                      7 hours ago











                    • @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                      – eerorika
                      7 hours ago











                    • Did you mean auto foo = [copy]...?

                      – Paul Sanders
                      4 hours ago







                    1




                    1





                    Nitpicking, but it would require the C++14 tag

                    – LWimsey
                    7 hours ago





                    Nitpicking, but it would require the C++14 tag

                    – LWimsey
                    7 hours ago













                    @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                    – eerorika
                    7 hours ago





                    @LWimsey Oh; Good point considering the C++11 tag; I didn't notice it.

                    – eerorika
                    7 hours ago













                    Did you mean auto foo = [copy]...?

                    – Paul Sanders
                    4 hours ago





                    Did you mean auto foo = [copy]...?

                    – Paul Sanders
                    4 hours ago











                    0














                    The reason is that operator() in lambda is const by default.



                    int main()

                    const int x = 0;
                    auto foo = [x](); // main::$_0::operator()() const
                    foo();



                    So you have to use mutable lambda:



                    int main()

                    const int x = 0;
                    auto foo = [x=x](); // main::$_0::operator()()
                    foo();






                    share|improve this answer




















                    • 1





                      mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                      – LWimsey
                      7 hours ago















                    0














                    The reason is that operator() in lambda is const by default.



                    int main()

                    const int x = 0;
                    auto foo = [x](); // main::$_0::operator()() const
                    foo();



                    So you have to use mutable lambda:



                    int main()

                    const int x = 0;
                    auto foo = [x=x](); // main::$_0::operator()()
                    foo();






                    share|improve this answer




















                    • 1





                      mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                      – LWimsey
                      7 hours ago













                    0












                    0








                    0







                    The reason is that operator() in lambda is const by default.



                    int main()

                    const int x = 0;
                    auto foo = [x](); // main::$_0::operator()() const
                    foo();



                    So you have to use mutable lambda:



                    int main()

                    const int x = 0;
                    auto foo = [x=x](); // main::$_0::operator()()
                    foo();






                    share|improve this answer















                    The reason is that operator() in lambda is const by default.



                    int main()

                    const int x = 0;
                    auto foo = [x](); // main::$_0::operator()() const
                    foo();



                    So you have to use mutable lambda:



                    int main()

                    const int x = 0;
                    auto foo = [x=x](); // main::$_0::operator()()
                    foo();







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 7 hours ago

























                    answered 7 hours ago









                    malchemistmalchemist

                    4242 silver badges12 bronze badges




                    4242 silver badges12 bronze badges







                    • 1





                      mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                      – LWimsey
                      7 hours ago












                    • 1





                      mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                      – LWimsey
                      7 hours ago







                    1




                    1





                    mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                    – LWimsey
                    7 hours ago





                    mutable will make operator() non-const, but for the captured object (without initializer), the type is presserved, which includes const in this case.

                    – LWimsey
                    7 hours ago

















                    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%2f56811624%2fdeducing-lambda-capture-types%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

                    ParseJSON using SSJSUsing AMPscript with SSJS ActivitiesHow to resubscribe a user in Marketing cloud using SSJS?Pulling Subscriber Status from Lists using SSJSRetrieving Emails using SSJSProblem in updating DE using SSJSUsing SSJS to send single email in Marketing CloudError adding EmailSendDefinition using SSJS

                    Кампала Садржај Географија Географија Историја Становништво Привреда Партнерски градови Референце Спољашње везе Мени за навигацију0°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.340°11′ СГШ; 32°20′ ИГД / 0.18° СГШ; 32.34° ИГД / 0.18; 32.34МедијиПодациЗванични веб-сајту

                    Кастелфранко ди Сопра Становништво Референце Спољашње везе Мени за навигацију43°37′18″ СГШ; 11°33′32″ ИГД / 43.62156° СГШ; 11.55885° ИГД / 43.62156; 11.5588543°37′18″ СГШ; 11°33′32″ ИГД / 43.62156° СГШ; 11.55885° ИГД / 43.62156; 11.558853179688„The GeoNames geographical database”„Istituto Nazionale di Statistica”проширитиууWorldCat156923403n850174324558639-1cb14643287r(подаци)