为什么std::is_same需要双括号

Why are double parentheses needed with std::is_same

本文关键字:same std is 为什么      更新时间:2023-10-16

我试图使用std::is_same来验证强类型枚举的底层类型,我注意到一个奇怪的情况,我需要使用双括号,但我不明白为什么。我把这个例子简化为:

#include <type_traits>
#include <cassert>
#include <stdint.h>
int main(int argc, char *argv[])
{
    assert((std::is_same<unsigned int,uint32_t>::value == true)); // OK
    assert((std::is_same<unsigned int,uint32_t>::value) == true); // OK
    //assert(std::is_same<unsigned int,uint32_t>::value == true); // Compile error
    static_assert(std::is_same<unsigned int,uint32_t>::value == true, "BAD"); // OK
    return 0;
}

编译错误:

isSameAssert.cpp:9:62: error: macro "assert" passed 2 arguments, but takes just 1
     assert(std::is_same<unsigned int,uint32_t>::value == true); // Compile error
                                                              ^
isSameAssert.cpp: In function ‘int main(int, char**)’:
isSameAssert.cpp:9:5: error: ‘assert’ was not declared in this scope
     assert(std::is_same<unsigned int,uint32_t>::value == true); // Compile error
     ^
make: *** [build/isSameAssert] Error 1

有人能解释一下吗?或者给我指一个可以解释的参考?

因为assert是一个宏,表达式assert(std::is_same<unsigned int,uint32_t>::value == true);似乎用两个参数调用assert,因为intuint32_t之间有逗号,所以编译器抱怨assert只接受一个参数,但提供了两个参数。

事实上,把它再次放在括号里解决了这个问题。