【问题标题】:Format foreach macros the same as loops with clang-format格式化 foreach 宏与使用 clang-format 的循环相同
【发布时间】:2018-07-26 09:31:45
【问题描述】:

我有一个类似于BOOST_FOREACHforeach 样式宏,我希望其格式类似于以下:

int bar(int a) { return ++a; }

int bar(int a) {
  a += 2;
  return ++a;
}

int foo(std::vector<int> a) {
  BOOST_FOREACH (auto i, a) {
    ++i;
  }

  for (auto &i : a) {
    ++i;
  }

  BOOST_FOREACH (auto i, a) {
    ++i;
    i += 2;
  }

  for (auto &i : a) {
    ++i;
    i += 2;
  }
}

问题是我用作基础的 LLVM 样式是这样的:

  BOOST_FOREACH (auto i, a) { ++i; }

  BOOST_FOREACH (auto i, a) {
    ++i;
    i += 2;
  }

即将短/单行 foreach 宏循环体放在一行上,尽管它不会对正常的 for 循环执行此操作。

我找不到clang-format 选项。以下是我尝试过的,以 LLVM 样式为基础:

BreakBeforeBraces: Custom
BraceWrapping:   
  AfterControlStatement: true

给予:

  BOOST_FOREACH (auto i, a)
  { ++i; }

  for (auto &i : a)
  {
    ++i;
  }

这看起来可能是一个错误?

BreakBeforeBraces: Custom
BraceWrapping:   
  AfterFunction: true

几乎是我想要的,但它显然也影响了我不想要的功能:

int foo(std::vector<int> a)
{
  BOOST_FOREACH (auto i, a) {
    ++i;
  }
...

投入

AllowShortFunctionsOnASingleLine: false

只影响单行的bar 而不是foreach 宏,所以我不认为这是因为clang-format 将宏视为函数定义。

我是否遗漏了什么,或者这可能是clang-format 中的错误?

【问题讨论】:

  • 您的.clang-format 是否包含ForEachMacros: [ BOOST_FOREACH ]
  • @Zeta 是的,这一切都在编辑 clang-format -style=LLVM -dump-config &gt; .clang-format 之后,其中包括该行,并带有 clang-format 6.0.0
  • 你试过AllowShortLoopsOnASingleLine: 'false' 吗?

标签: c++ clang-format


【解决方案1】:

我不认为你错过了什么。我同意它看起来像 clang-format 中的一个错误。

AfterControlStatement 设置在格式化BOOST_FOREACH 循环时无法正常工作,AfterFunction 会影响它,但实际上不应该。对我来说,ForEachMacros 设置根本不起作用,这可能是问题的一部分(当我从 for-each 宏列表中删除 BOOST_FOREACH 时,行为是相同的)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多