clang-format嵌套大括号初始化代码格式化配置问题求助
clang-format嵌套大括号初始化格式配置问题
期望格式及规则
期望格式化后代码呈现如下效果:
auto test = TheThing{ Arg1{ blorp, bleep, bloop, blop, blip }, Arg2{ blorp, bleep, bloop, blop, blop, blip } };
期望的格式化规则:
- 参数过长无法单行容纳时,每个参数单独占一行
- 参数采用缩进方式,而非与首个左大括号末端对齐
- 参数包含的嵌套参数列表保持单行显示
实际格式化结果
clang-format当前输出样式:
auto test = TheThing{ Arg1{ blorp, bleep, bloop, blop, blip }, Arg2{ blorp, bleep, bloop, blop, blop, blip } };
不符合预期的行为:
- 第一个参数仍与左大括号位于同一行
- 参数采用对齐方式而非缩进
当前clang-format配置
--- BasedOnStyle: Microsoft AccessModifierOffset: -4 AlignArrayOfStructures: Left AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: InlineOnly AllowShortLambdasOnASingleLine: Inline AlignTrailingComments: true BraceWrapping: AfterCaseLabel: true AfterClass: true AfterControlStatement: Always AfterEnum: true AfterFunction: true AfterNamespace: true AfterStruct: true AfterUnion: true AfterExternBlock: true BeforeCatch: true BeforeElse: true BeforeLambdaBody: true BeforeWhile: true IndentBraces: true SplitEmptyFunction: false BreakBeforeBraces: Allman BreakConstructorInitializers: AfterColon ColumnLimit: 120 DerivePointerAlignment: false FixNamespaceComments: false IncludeBlocks: Regroup IndentWidth: 4 NamespaceIndentation: All PointerAlignment: Left ReferenceAlignment: Left SortIncludes: Never SpaceAfterCStyleCast: false SpaceAfterLogicalNot: false SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpaceAfterTemplateKeyword: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true TabWidth: 4 UseTab: Always AlignAfterOpenBracket: AlwaysBreak AllowAllArgumentsOnNextLine: false AllowAllConstructorInitializersOnNextLine: false AllowAllParametersOfDeclarationOnNextLine: false BinPackArguments: false BinPackParameters: false ConstructorInitializerAllOnOneLineOrOnePerLine: true Cpp11BracedListStyle: false SpaceBeforeCpp11BracedList: false
解决方案
调整以下关键配置项即可实现预期格式:
AlignAfterOpenBracket: DontAlign:关闭参数与左大括号末端的对齐逻辑,改用缩进格式AllowAllArgumentsOnNextLine: true:强制将所有参数换行到新行,避免第一个参数留在左大括号所在行- 保持
BinPackArguments: false和Cpp11BracedListStyle: false不变,确保参数不打包且大括号列表格式符合需求
修改后的核心配置片段:
AlignAfterOpenBracket: DontAlign AllowAllArgumentsOnNextLine: true BinPackArguments: false Cpp11BracedListStyle: false
调整后clang-format会输出符合预期的格式:每个参数单独一行、使用缩进、嵌套参数保持单行。
内容的提问来源于stack exchange,提问作者Breealzibub
相关产品推荐
相关产品推荐

