Skip to content

[SUGGESTION] Implement local functions (as CPP1 lambda-s) #1238

Open
@jamadagni

Description

@jamadagni

Background:

This request stems from #1234. I am not sure if #714 addresses this too but since @hsutter said he would like to do it, I assume this is separate and file this just to keep track of the matter.

Current situation:

Currently it is required to declare local functions (which include captures) as:

func := :() = { std::cout << "Price = " << price$ << "\n"; };

And this is rewritten into the following CPP1:

auto func {[_0 = price]() mutable -> void{
    std::cout << "Price = " << _0 << "\n";
}}; 

Current difficulty:

However, :=:()= is quite abstruse to decipher, which is why I had to ask #1234. IIANM CPP2 wants to cut out such abstruseness in the language as far as possible.

So I tried to just write a local function, but:

func : () = std::cout << "Price = " << price$ << "\n";

gives:

test4b.cpp2(4,41): error: $ (capture) cannot appear here - it must appear in an anonymous expression function, a postcondition, or an interpolated string literal (at '$')

and even without the capture:

greet : () = std::cout << "Hello\n";

gives:

test4c.cpp2(2,5): error: (temporary alpha limitation) local functions like 'greet: (/*params*/) = {/*body*/}' are not currently supported - write a local variable initialized with an unnamed function like 'greet := :(/*params*/) = {/*body*/};' instead (add '=' and ';')

Request:

I am not an expert but I am not sure there is any effective difference between a local function and a named lambda.

Given that CPP2 already rewrites code to overcome CPP1 limitations, I hence feel it should just automatically rewrite the local function as a named lambda. Hence the recommendation to “add = and ;” (which seems to be missing the :) should no longer be made and CppFront should silently do this rewrite for us instead.

This would also adhere to the one declaration syntax principle, rather than having the user to write :=:()= io the normal :()= for effectively the same purpose.

IIANM this would mean that the final ; should also not be there, as it is there only because this is currently treated as a lambda variable definition rather than a function definition.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions