Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing outer scope name in a lambda, is g++ or Visual or neither, right?

Tags:

c++

lambda

Code:

auto main() -> int
{
    int b = 42;
    auto lambasta = [&]()
    {
        using B_type = decltype( b );
        return B_type{};
    };
    (void) lambasta;
}

Compiles with no diagnostic with MinGW g++ 6.3.0 -std=c++14 -Wall -pedantic-errors. Fails to compile with Visual C++ 2015 update 3,

foo.cpp(6): error C2065: 'b': undeclared identifier
like image 546
Cheers and hth. - Alf Avatar asked Mar 01 '17 08:03

Cheers and hth. - Alf


People also ask

What is the type of a lambda?

A type lambda lets one express a higher-kinded type directly, without a type definition. For instance, the type above defines a binary type constructor, which maps arguments X and Y to Map[Y, X] . Type parameters of type lambdas can have bounds, but they cannot carry + or - variance annotations.

How do you capture a variable in lambda function?

Much like functions can change the value of arguments passed by reference, we can also capture variables by reference to allow our lambda to affect the value of the argument. To capture a variable by reference, we prepend an ampersand ( & ) to the variable name in the capture.

What is the lambda function in C++?

C++ Lambda expression allows us to define anonymous function objects (functors) which can either be used inline or passed as an argument. Lambda expression was introduced in C++11 for creating anonymous functors in a more convenient and concise way.

What is a lambda capture list?

The capture list defines the outside variables that are accessible from within the lambda function body. The only capture defaults are. & (implicitly capture the used automatic variables by reference) and. = (implicitly capture the used automatic variables by copy).


1 Answers

Possible workaround:

template<typename T>
struct wrapper
{
    using wrapped_t = T;
};

auto main() -> int
{
    int b = 42;
    auto lambasta = [&, a = wrapper<decltype(b)>()]()
    {
        using B_type = typename decltype( a ) ::wrapped_t;
        return B_type{};
    };
    (void) lambasta;
}

Works on GCC 6.3 and MSVC 2015 up 3

like image 165
Evgeniy Avatar answered Sep 21 '22 10:09

Evgeniy