You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让clang-format不为带requires子句的函数左大括号前换行?

解决Clang-format格式化带requires子句函数时自动换行大括号的问题

使用Clang-format格式化代码时,带requires子句的函数左大括号前总会被自动插入换行。

原代码:

constexpr auto size() const noexcept
  requires(!Unique) {
    return stdr::fold_left(views | stdv::transform(stdr::size), 0, std::plus<int>{});
}

格式化后代码:

constexpr auto size() const noexcept
  requires(!Unique)
{
    return stdr::fold_left(views | stdv::transform(stdr::size), 0, std::plus<int>{});
}

若你尝试过以下配置但未生效:

RequiresClausePosition: WithPreceding
BraceWrapping:
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false
BreakBeforeBraces: Custom

可以通过修改BreakBeforeBraces的取值解决问题:将BreakBeforeBraces从Custom改为Attach,同时保留RequiresClausePosition: WithPreceding配置。

调整后的完整配置示例:

RequiresClausePosition: WithPreceding
BreakBeforeBraces: Attach
BraceWrapping:
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false

原理说明:当BreakBeforeBraces设为Attach时,Clang-format会将函数的左大括号直接附着在requires子句所在行的末尾,不会插入换行。此前使用Custom模式时,即使设置了AfterFunction: false,Clang-format对带requires子句的函数处理逻辑也会导致换行,切换为Attach模式即可符合预期。

内容的提问来源于stack exchange,提问作者Sourav Kannantha B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:50:10