【问题标题】:error: macro "assert" passed 2 arguments, but takes just 1错误:宏“断言”传递了 2 个参数,但只需要 1 个
【发布时间】:2021-10-31 01:50:25
【问题描述】:
vector<string> foo(vector<string> s) { return s; }
assert(foo(vector<string>{"hello", "world"}) ==
         vector<string>{"hello", "world"});
  • 错误:宏“assert”传递了 2 个参数,但只需要 1 个
  • 错误:未在此范围内声明“断言”

也许在 gcc 11.1.0 中定义断言

#  define assert(expr)                          \
     (static_cast <bool> (expr)                     \
      ? void (0)                            \
      : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))

编译器标志是

 -Wall -std=c++20

【问题讨论】:

    标签: c++


    【解决方案1】:

    预处理器只对 C++ 的语法有一个原始的理解,特别是它把任何没有括在括号中的逗号作为参数分隔符。 assert 调用中有两个逗号,括号中只有一个,所以宏认为它得到了两个参数,如下所示

    foo(vector<string>{"hello", "world"}) == vector<string>{"hello"
    "world"});
    

    将表达式括在括号中以防止这种情况发生。

    // Note: Double parens
    assert((foo(vector<string>{"hello", "world"}) ==
            vector<string>{"hello", "world"}));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 2021-07-23
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多