如何避免clang-format在构造函数初始化列表的大括号后换行
clang-format 构造函数初始化列表大括号格式化调整方案
问题场景
期望格式化结果:
A::A() : index{1}, string_one{"some pretty string"}, string_two{"another pretty string"} { }
实际格式化结果:
A::A() : index{1}, string_one{"some pretty string"}, string_two{ "another pretty string"} { }
需求:避免成员名与大括号初始化实参之间换行,将整个成员初始化项移至新行;括号初始化可正常工作,需适配大括号初始化场景。
当前.clang-format配置:
--- BasedOnStyle: LLVM Language: Cpp Standard: c++17 TabWidth: 4 IndentWidth: 4 AccessModifierOffset: -4 ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 NamespaceIndentation: All ColumnLimit: 80 BinPackArguments: true BinPackParameters: true AllowShortFunctionsOnASingleLine: None ...
解决方案
在.clang-format中添加或修改以下配置项:
ConstructorInitializerAllOnOneLineOrOnePerLine: true BinPackConstructorInitializers: false
配置说明
ConstructorInitializerAllOnOneLineOrOnePerLine: true:强制构造函数初始化列表的每个成员要么全部在一行,要么单独占一行。触发换行时,会将整个成员初始化项(成员名+大括号+实参)整体移至新行,避免拆分单个项。BinPackConstructorInitializers: false:关闭初始化项的打包功能,当列宽不足时,自动将后续初始化项移至新行,确保每个项的完整性。
添加这两项配置后,clang-format会输出你期望的格式化结果。
内容的提问来源于stack exchange,提问作者Guillermo Frontera
相关产品推荐
相关产品推荐

