Why is clang-format screwing up this code?

Viewed 275

My code base has a lot of std::variant types and functions that use std::visit to implement different behavior based on the actual type.

I am using clang-format, and sometimes it scrambles the functions that use std::visit. I have a function called visitor that builds a visitor from a bunch of lambdas. It appears that when the lambdas declare a return type of auto&, clang-format decides to start breaking lines after the closing brace of each lambda, leaving the commas on the left margin.

Here is a sample function, with the clang-format formatting:

struct A {};
struct B {};
typedef std::variant<A, B> AB;

template <class... Ts>
struct visitor : Ts... {
    using Ts::operator()...;
};
template <class... Ts>
visitor(Ts...) -> visitor<Ts...>;

AB& f(AB& ab) {
    auto v = visitor{[&](const A& a) -> auto& {std::cout << "A" << std::endl;
    return ab;
}
, [&](const B& b) -> auto& {
    std::cout << "B" << std::endl;
    return ab;
}
,
};
std::visit(v, ab);
}

Here's how it should look (which I get if I remove -> auto&):

AB& f(AB& ab) {
    auto v = visitor{
        [&](const A& a) {
            std::cout << "A" << std::endl;
            return ab;
        },
        [&](const B& b) {
            std::cout << "B" << std::endl;
            return ab;
        },
    };
    std::visit(v, ab);
}

Here is my .clang-format file:

BasedOnStyle:  Google
ColumnLimit: 120
IndentWidth: 4
AccessModifierOffset: -4
AlignAfterOpenBracket: DontAlign

I'm using Clang 9.

Does anyone how know I can fix this?

0 Answers
Related