2 ms·
Ask HN: What is this weird (Flex layout) C++ code?
Obviously, I am way behind in modern C++ syntax past my initial courses. While looking at the WebKit source code in order to understand the flex layout, I see this code:
auto performMainAxisLayout = [&] {
computeLogicalWidthForFlexItems(flexItems, lineRange, availableLogicalHorizontalSpace, flexRects);
distributeMarginAutoInMainAxis(flexItems, lineRange, availableLogicalHorizontalSpace, flexRects);
justifyFlexItems(flexItems, lineRange, availableLogicalHorizontalSpace, flexRects);
};
performMainAxisLayout();
auto performCrossAxisLayout = [&] {
auto availableLogicalVerticalSpace = lineHeightList[index];
computeLogicalHeightForFlexItems(flexItems, lineRange, availableLogicalVerticalSpace, flexRects);
distributeMarginAutoInCrossAxis(flexItems, lineRange, availableLogicalVerticalSpace, flexRects);
alignFlexItems(flexItems, lineRange, { lineTop, availableLogicalVerticalSpace }, flexRects);
lineTop += availableLogicalVerticalSpace;
};
performCrossAxisLayout();
This can be seen here[0] for more context. My question is - what is this [&] thing? And I cannot find the method named performMainAxisLayout() or performCrossAxisLayout() defined anywhere in the Layout class either. My assumption was that here, a structure/literal class is being built and the methods are on that class but the Layout class don't have them either.
Where can I learn more about this syntax or modern C++ quick overview in general?
[0]. https://github.com/WebKit/WebKit/blob/main/Source/WebCore/layout/formattingContexts/flex/FlexLayout.cpp#L506-L536
EDIT: Fixed title typo.
- compressedgas 3y agoThat is a C++ Lambda: https://en.cppreference.com/w/cpp/language/lambda https://en.cppreference.com/w/cpp/language/lambda
- wg0 3y agoInteresting. Didn't know that. Now it makes sense. So they inline the steps and then call them as a named method. Beautiful, very very readable once you know the syntax.
- codetrotter 3y agoAndreas Kling writes similar looking code for his web browser and his operating system. Watch some of his videos on YouTube. https://youtube.com/@awesomekling https://youtube.com/@awesomekling