Clang-format: 设置控制 C + + 属性

通过对 Clang-格式样式选项的搜索,我似乎找不到一种方法来控制 C + + 属性放置的行为。

例如,以这两个声明为例,第一个声明不会溢出列限制,第二个声明会溢出列限制:

template <typename TChar>
[[gnu::always_inline]]
static ptr<TChar> within_limit(ptr<TChar> first, ptr<TChar> last);


template <typename TChar, typename FApply, typename... FApplyRest>
[[gnu::always_inline]]
static ptr<TChar> overflow(ptr<TChar> first, ptr<TChar> last, const FApply& apply, const FApplyRest&... apply_rest);

无论我如何调整我的 .clang-format,输出是这样的一些变体:

[[gnu::always_inline]] static ptr<TChar> within_limit(ptr<TChar> first, ptr<TChar> last);


[[gnu::always_inline]] static ptr<TChar>
overflow(ptr<TChar> first, ptr<TChar> last, const FApply& apply, const FApplyRest&... apply_rest);

将属性与类型放在同一行是相当不可读的(对我来说) ,所以我希望 clang-format不要这样做。使用 __attribute__((always_inline))表现出同样的行为。在单个列表([[noreturn, gnu::cold]])中指定多个属性会导致重新格式化(由于我不清楚的原因而改为 [[ noreturn, gnu::cold ]])。格式化程序至少对属性有一些基本的理解。

SO: 有没有办法让 clang-format把属性放在它们自己的行上(C + + 等同于 BreakAfterJavaFieldAnnotations) ?


试图解决问题

使用 // clang-format off/// clang-format on只是 好吧的权宜之计,但对于一个永久性的解决方案来说,它显然太笨拙了。我仍然希望声明格式正确。除此之外,该项目还需要使用许多属性,因此在任何地方使用 clang-format注释都可以说是不太可读的。

使用 CommentPragmas理论上可以让我在禁用时更本地化,但是输出仍然很奇怪:

template <typename TChar>
[[gnu::always_inline]] // NO-FORMAT: Attribute
static ptr<TChar>
within_limit(ptr<TChar> first, ptr<TChar> last);
2578 次浏览

This is not a "solution", but a general workaround for preventing clang-format (and other formatters) from removing line breaks.

Just add an empty line comment at the end of a line like so:

template <typename TChar>
[[gnu::always_inline]] //
static ptr<TChar>
within_limit(ptr<TChar> first, ptr<TChar> last);


template <typename TChar, typename FApply, typename... FApplyRest>
[[gnu::always_inline]] //
static ptr<TChar>
overflow(ptr<TChar> first, ptr<TChar> last, const FApply& apply, const FApplyRest&... apply_rest);

It can't merge the lines now, as this would comment out the entire rest of the line.

For this specific example, it's unfortunately not perfect, as it also seems to introduce a second line break after the return type (which looks arguably worse than having everything on a single line). Nontheless I thought this might come in handy in some scenarios (although I haven't personally used it all that much either).

It's at least a lot less verbose than turning off clang-format completely for just a single line.