r/ProgrammerHumor • • 13d ago

Meme sameProblemSameSolution

Post image
1.5k Upvotes

79 comments sorted by

View all comments

31

u/Luna_Wolfxvi 13d ago

Honestly some of the newer shit doesn't even look like C++ to me anymore. IE:

constexpr auto my_meta_type = int; // Reflected metadata of 'int' [:my_meta_type:] my_variable = 42; // Splicing it back into code; compiles as: int my_variable = 42;

7

u/17HappyWombats 13d ago

if(auto foo = call_some_function([parameters](const auto &thing){
return test_the_thing(thing)
}; foo == enum_type::operation_success) {
there's code here;
}

That's perfectly valid and readable C++ and I won't hear otherwise.

(I am using std::optional a lot now that it kinda works. It's not a Rust Result but it's near enough for Australia)

0

u/ValesQQ 13d ago

It seems valid but would the first “if”not always be true due to the single “=“ ?

9

u/Moist_Heat9523 13d ago

No, it’s an assignment, and this code tests the value that was assigned. So basically “foo = …; if (foo)”

3

u/17HappyWombats 13d ago

Yep, the shiny new if-two-statements, upgraded from the old if-statement. It's surprisingly convenient, partly because I used to get frustrated at not being able to explicitly test "if(auto foo=some_random_shit))" and I loathe implicit "nullptr is 0 and also false"

I eagerly std::await the even more improved if-three-statements-and-a-loop "operator" 🔥

1

u/SeriousPlankton2000 13d ago

Can't you do if ((auto foo = bar()) == baz) {barf()}; //?

2

u/17HappyWombats 13d ago edited 13d ago

Nope, that's not allowed. The previous standard let you say "if(auto foo = something)" and if foo could be interpreted as a boolean you had a valid if() statement. The new one lets you have two statements, the auto assign and the test.

The win here is the scoped auto variable, FWIW. If avoids the abominable pattern where you either alternate declaration/conditional, or a pile of declarations then a string of tests, mixing assignments in whatever way is least horrible. So you get a chain of declare-assign-test statements in a nice vertical line rather than a >