加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Xcode [c]中定义lambda(assert.h)中的lambda时,为类似函数的宏

发布时间:2020-12-15 01:41:39 所属栏目:百科 来源:网络整理
导读:我正在使用assert.h中的断言宏 我已经定义了lambda来执行断言检查. int val1 = 0;int val2 = 1;const auto check = [val1,val2]()- bool{ return val1 val2;};// no error for this callassert(check() "Test is failed");// no error for this callassert([
我正在使用assert.h中的断言宏
我已经定义了lambda来执行断言检查.

int val1 = 0;
int val2 = 1;

const auto check = [val1,val2]()-> bool
{
    return val1 < val2;
};
// no error for this call
assert(check() && "Test is failed");

// no error for this call
assert([=]()-> bool
       {
           return val1 < val2;
       }() && "Test is failed");

06001

为什么我要来

too many arguments provided to function-like macro invocation

当我使用assert宏并在捕获列表中定义带有多个参数的lambda时,编译错误?

解决方法

问题是捕获列表中的逗号.

预处理器对C语法的理解非常有限,它主要进行简单的文本替换.如果逗号不在匹配的内括号之间(当然不是字符串文字的一部分),则预处理器会将其视为宏调用的参数的分隔符.

所以预处理器认为你用两个参数调用assert [this和第一个逗号后面的其余东西,这会产生错误.

您可以使用一组额外的括号来修复此错误:

int i = -7,j = 7;
assert(([i,j](){return i + j;}()));

对于标准爱好者:

The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the list of
arguments for the function-like macro. The individual arguments within the list are separated by comma
preprocessing tokens,but comma preprocessing tokens between matching inner parentheses do not separate
arguments.
If there are sequences of preprocessing tokens within the list of arguments that would otherwise
act as preprocessing directives,155 the behavior is undefined.

N4140中的16.3 / 11,强调我的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读