hsutter / cppfront

A personal experimental C++ Syntax 2 -> Syntax 1 compiler
Other
5.41k stars 234 forks source link

[SUGGESTION] Allow concept type constraints with the `_` wildcard (C++ constrained `auto`) #1166

Closed bluetarpmedia closed 1 month ago

bluetarpmedia commented 1 month ago

(I can't find an issue/discussion about this so apologies if I've missed it.)

Suggestion Allow concept placeholder type constraints in Cpp2 with the _ wildcard, as an equivalent of constrained auto in C++.

I'd like to write the Cpp2 equivalent of the following C++:

void print(std::ranges::forward_range auto const& r) {
  // etc
}

std::vector<int> vi = get_data();
print(vi);

This works in Cpp2 (see example):

print: <Rng>(r: Rng) requires (std::ranges::forward_range<Rng>) = {

}

But it reads quite verbose to me compared to the original C++. Something like the following would be closer to the original, I think:

print: (r: std::ranges::forward_range _) = {

}

Will your feature suggestion eliminate X% of security vulnerabilities of a given kind in current C++ code? No

Will your feature suggestion automate or eliminate X% of current C++ guidance literature? No

hsutter commented 1 month ago

Edited: ~Thanks, good catch! I see there isn't a similar forward algorithm so I just need to adjust this for move...~

Sorry, replied on wrong issue...

hsutter commented 1 month ago

Thanks! I've added is constraints on wildcarded parameters and locals.

With the above commit, the following now works (and the last line would be an error if not commented out):

print: (r: _ is std::regular) = {
    std::cout << "satisfies std::regular\n";
}

print: (_) = {
    std::cout << "fallback\n";
}

irregular: type = {}

main: () = {
    print(42);           // prints: satisfies std::regular
    print(irregular());  // prints: fallback

    ok : _ is std::regular = 42;
    //err: _ is std::regular = irregular();
}
bluetarpmedia commented 1 month ago

Nice work Herb!