Skip to content

[QUESTION] Is &$* a new cpp2 idiom? #247

Closed
@filipsajdak

Description

@filipsajdak

As there is no possibility of passing a reference to the anonymous function (aka. lambda), you need to capture a variable as a pointer. That makes a new idiom emerge from the code: &$* - capture variable by pointer (and use as a reference).

The following code:

main: () -> int = {
    i := 42;

    l := :() = {
        std::cout << i&$* << std::endl;
    };

    l();
}

Will generate (skipping boilerplate):

[[nodiscard]] auto main() -> int{
    auto i {42}; 

    auto l {[_0 = (&i)](){                                    // capture by pointer
        std::cout << *cpp2::assert_not_null(_0) << std::endl; // dereference in place of use
    }}; 

    std::move(l)();
}

Or maybe I have missed something?


For all that wanders what i&$* means (please remember that cppfront uses postfix operators - https://github.com/hsutter/cppfront/wiki/Design-note%3A-Postfix-operators). I will add parentheses to explain:

i& - address of i,
(i&)$ - $ captures the value on the left (in that case, it is a pointer to i),
( (i&)$ )* - * dereference the value captured by $ (in that case, it is a pointer to i)

So, effectively i&$* is a reference to i that is captured by a lambda.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions