微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 为什么这个“调用”断言看到两个参数而不仅仅是一个?

鉴于 this test program
#include <cassert>
#include <string>
#include <type_traits>

const std::string& const_string = "bla";
std::string const & string_const = "blabla";

static_assert(std::is_same<decltype(const_string),decltype(string_const)>::value,"Uhoh");

int main()
{
    assert(std::is_same<decltype(const_string),decltype(string_const)>::value);
}

其中断言两种类型在编译时和使用C的断言在运行时是相同的. Clang,MSVC2015和GCC都报告了同样的错误,所以我很确定it’s me

main.cpp:13:49: error: too many arguments provided to function-like macro invocation
    assert(std::is_same<decltype(const_string),decltype(string_const)>::value);
                                                ^
/usr/include/assert.h:91:10: note: macro 'assert' defined here
# define assert(expr)                                                   \
         ^

我只是没有在断言中看到两个参数.更重要的是,static_assert工作得很好……那么这里发生了什么?

解决方法

C预处理器不识别C模板语法,因此模板括号<和>预处理器不会将它们视为分组标记,它们被视为简单字符.

这意味着预处理器将模板参数之间的逗号视为宏参数分隔符,如下所示:

assert(
    std::is_same<decltype(const_string),decltype(string_const)>::value);

要强制预处理器将表达式看作单个语句,只需将assert参数包装在另一组括号中:

assert((std::is_same<decltype(const_string),decltype(string_const)>::value));

static_assert没有这个限制,因为它是一个C++ keyword,而不是像assert()那样的预处理器宏.这意味着它完全支持C语法并正确查看模板参数.

原文地址:https://www.jb51.cc/c/111007.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐