【问题标题】:Why doesn't clang-format break before braces of getter?为什么clang-format在getter大括号之前不中断?
【发布时间】:2020-03-06 23:45:24
【问题描述】:

相关帖子how to make clang-format add new line before opening brace of a function?的回答无济于事。

我在 Windows 上的 Eclipse CDT 中使用带有 Cppstyle 的 clang-format 9.0.0。 clang-format 像这样格式化以下 getter:

int returnNumber() { return 3; }

但我更喜欢这种格式

int returnNumber()
{
    return 3;
}

我无法让 clang-format 做到这一点,无论是打破风格 BS_Allman 还是自定义风格。除了手动格式化还有其他解决方案吗?

我的示例源文件如下所示:

头文件.h

#pragma once

namespace Test
{

class MyClass
{
public:
    int returnNumber() { return 3; }
};

} /* namespace Test */

而我的配置文件是这样的:

Language: Cpp

AlwaysBreakTemplateDeclarations: 'true'

BreakBeforeBraces: Allman

ColumnLimit: '80'

IndentWidth: '2'

NamespaceIndentation: None

Standard: Cpp11

TabWidth: '2'

UseTab: Always

PointerAlignment: Left

AlignAfterOpenBracket: DontAlign

BreakConstructorInitializers: AfterColon

MaxEmptyLinesToKeep: 2

【问题讨论】:

  • clang-format 应该能够做到这一点。您可以使用相同的配置在源文件上手动运行它,看看会发生什么?
  • 当我从控制台使用clang-format Header.h > Out.h 运行它时,我得到了相同的(坏的)结果:getter 被压缩成一行。
  • 你能用你正在使用的clang-format.config文件更新问题吗?

标签: c++ code-formatting clang-format


【解决方案1】:

你的配置的问题是你错过了这个用短函数控制clang-format行为的选项。

将此添加到您的配置中,一切都会好起来的:

AllowShortFunctionsOnASingleLine: None

引用clang-format documentation

AllowShortFunctionsOnASingleLine (ShortFunctionStyle)

取决于值,int f() { return 0; } 可以放在一行。

可能的值:

  • SFS_None(配置中:无)永远不要将函数合并到一行中。

  • SFS_InlineOnly(配置中:InlineOnly)仅合并类中定义的函数。与“内联”相同,但不是 暗示“空”:即顶级空函数也不合并。

  • SFS_Empty(配置中:空)仅合并空函数。

  • SFS_Inline(在配置中:内联)仅合并类内定义的函数。表示“空”。

  • SFS_All(配置中:全部)合并所有适合单行的函数。

【讨论】:

  • 出于某种原因AllowShortFunctionsOnASingleLine: None 没有做任何事情。恐怕它可能与另一种选择相冲突。但我现在真的迷路了。
猜你喜欢
  • 2017-10-17
  • 2019-03-20
  • 1970-01-01
  • 2015-06-11
  • 2016-05-20
  • 2020-08-10
  • 1970-01-01
  • 2019-01-27
  • 2020-04-04
相关资源
最近更新 更多