首页 > 解决方案 > 为什么clang-format在getter大括号之前不中断?

问题描述

相关帖子的答案如何在打开函数的大括号之前使 clang-format 添加新行?没有帮助。

我在 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

标签: c++code-formattingclang-format

解决方案


您的配置的问题是您错过了控制clang-format短函数行为的此选项。

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

AllowShortFunctionsOnASingleLine: None

引用clang-format 文档

AllowShortFunctionsOnASingleLine (ShortFunctionStyle)

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

可能的值:

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

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

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

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

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


推荐阅读