【问题标题】:clang-format: Setting to control C++ attributesclang-format:设置以控制 C++ 属性
【发布时间】:2018-01-26 04:26:24
【问题描述】:

搜索Clang-Format Style Options,我似乎找不到控制 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 cmets 可以说是可读性较差。

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

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

【问题讨论】:

  • 我正在为 [[deprecated]] 属性说明符寻找相同问题的解决方案。据我所知,这可能是 clang 格式的缺失功能。你找到解决办法了吗?
  • 自 Clang 6 起尚未添加 -- clang.llvm.org/docs/ClangFormatStyleOptions.html.
  • [[nodiscard]] 属性说明符的类似问题。使用其他 clang 格式属性的任何解决方法?
  • clang-formatv12.0.0 中似乎还没有这个?!我真的很想使用[[nodiscard]],但是这个缺失的特性“破坏”了我们使用尾随返回类型的良好对齐的函数:[[nodiscard]] auto f() -&gt; void;
  • v13.0.0:不。很伤心。

标签: clang-format


【解决方案1】:

这不是“解决方案”,而是防止 clang-format(和其他格式化程序)删除换行符的一般解决方法。

只需在行尾添加一个空行注释,如下所示:

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 格式要简单得多。

【讨论】:

    猜你喜欢
    • 2018-05-20
    • 1970-01-01
    • 2018-06-25
    • 2013-04-24
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多