为什么 clang-format 在 getter 的大括号之前没有中断?

Why doesn't clang-format break before braces of getter?

相关post的回答没有帮助

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

int returnNumber() { return 3; }

但我更喜欢这种格式

int returnNumber()
{
    return 3;
}

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

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

Header.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 行为的选项。

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

AllowShortFunctionsOnASingleLine: None

引自clang-format documentation

AllowShortFunctionsOnASingleLine (ShortFunctionStyle)

Dependent on the value, int f() { return 0; } can be put on a single line.

Possible values:

  • SFS_None (in configuration: None) Never merge functions into a single line.

  • SFS_InlineOnly (in configuration: InlineOnly) Only merge functions defined inside a class. Same as “inline”, except it does not implies “empty”: i.e. top level empty functions are not merged either.

  • SFS_Empty (in configuration: Empty) Only merge empty functions.

  • SFS_Inline (in configuration: Inline) Only merge functions defined inside a class. Implies “empty”.

  • SFS_All (in configuration: All) Merge all functions fitting on a single line.