Lambda capture as const reference?

后端 未结 8 1720
春和景丽
春和景丽 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:10

    In c++14 using static_cast / const_cast:

    [&best_string = static_cast(best_string)](const string& s)
    {
        best_string = s; // fails
    };
    

    DEMO


    In c++17 using std::as_const:

    [&best_string = std::as_const(best_string)](const string& s)
    {
        best_string = s; // fails
    };
    

    DEMO 2

提交回复
热议问题