Clang-Format不会缩进头文件中的模板函数

时间:2019-09-27 15:21:48

标签: clang-format

我在使用clang格式时遇到此问题,无法正确缩进头文件。例如,我在一个类中有一个模板函数,希望它的格式如下:

template <class T>
class Thing {
public:
    T function() {
        stuff();
        return T;
    }
}

我感觉这种缩进会自动发生,但是事实并非如此。当我运行Clang格式时,我的功能代码像这样缩进:

template <class T>
class Thing {
public:
    T function() {
    stuff();
    return T;
    }
}

如何获取头文件中的代码,使其格式像最上面的而不是最下面的一样?

下面是我的.clang格式文件:

BasedOnStyle: LLVM
AccessModifierOffset: -4
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: true
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBraces: Custom
BraceWrapping:
  AfterClass: false
  AfterControlStatement: false
  AfterEnum: false
  AfterFunction: false
  AfterNamespace: false
  AfterStruct: false
  AfterUnion: false
  AfterExternBlock: false
  BeforeCatch: false
  BeforeElse: false
  IndentBraces: false
  SplitEmptyFunction: false
BreakConstructorInitializers: AfterColon
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 2
Cpp11BracedListStyle: true
DerivePointerAlignment: false
IndentCaseLabels: false
IndentWidth: 4
Language: Cpp
NamespaceIndentation: All
PenaltyBreakBeforeFirstCallParameter: 0
PenaltyBreakComment: 2000
PenaltyBreakString: 3000
PenaltyBreakFirstLessLess: 1000
PenaltyExcessCharacter: 100000
PenaltyReturnTypeOnItsOwnLine: 10000
PointerAlignment: Left
SortIncludes: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInParentheses: false
Standard: Cpp11
UseTab: ForIndentation

1 个答案:

答案 0 :(得分:3)

我在this online clang format generator中打开了您的配置文件,并寻找了适用于您的示例代码的设置。

这看起来如何?

BasedOnStyle: LLVM
AccessModifierOffset: '-2'
AllowShortFunctionsOnASingleLine: Inline
BreakBeforeBraces: Custom
BreakConstructorInitializers: AfterColon
ColumnLimit: '80'
ConstructorInitializerIndentWidth: '4'
ContinuationIndentWidth: '2'
IndentWidth: '2'
Language: Cpp
NamespaceIndentation: All
PenaltyBreakBeforeFirstCallParameter: '0'
PenaltyBreakComment: '2000'
PenaltyBreakFirstLessLess: '1000'
PenaltyBreakString: '3000'
PenaltyExcessCharacter: '100000'
PenaltyReturnTypeOnItsOwnLine: '10000'
PointerAlignment: Left
SpaceBeforeParens: ControlStatements
Standard: Cpp11
UseTab: Never

我认为也许UseTab: NeverAccessModifierOffset: '-2'是相关设置。当IndentWidth:AccessModifierOffset之间的关系比前者的缩进更大时,似乎还没有任何联系。

如果这些不是您要查找的设置,zed0是一种易于使用的资源,可用来创建可以使用的clang格式文件。