Lambda capture as const reference?

后端 未结 8 1709
春和景丽
春和景丽 2020-11-30 19:33

Is it possible to capture by const reference in a lambda expression?

I want the assignment marked below to fail, for example:

#include 

        
8条回答
  •  爱一瞬间的悲伤
    2020-11-30 20:08

    I guess if you're not using the variable as a parameter of the functor, then you should use the access level of the current function. If you think you shouldn't, then separate your lambda from this function, it's not part of it.

    Anyway, you can easily achieve the same thing that you want by using another const reference instead :

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    int main()
    {
        string strings[] = 
        {
            "hello",
            "world"
        };
        static const size_t num_strings = sizeof(strings)/sizeof(strings[0]);
    
        string best_string = "foo";
        const string& string_processed = best_string;
    
        for_each( &strings[0], &strings[num_strings], [&string_processed]  (const string& s)  -> void 
        {
            string_processed = s;    // this should fail
        }
        );
        return 0;
    }
    

    But that's the same as assuming that your lambda have to be isolated from the current function, making it a non-lambda.

提交回复
热议问题