【发布时间】:2017-10-19 16:57:30
【问题描述】:
下面的代码
#include<iostream>
template<bool T>
class Invert
{
public:
static bool const result = !T;
};
int main()
{
bool test = Invert<1-1>::result;
std::cout << "test " <<test << "\n";
bool test1 = Invert<1 + 1>::result;
std::cout << "test1 " << test1 << "\n";
bool test2 = Invert<1 || 1>::result;
std::cout << "test2 " << test2 << "\n";
bool test3 = Invert<0 && 1>::result;
std::cout << "test3 " << test3 << "\n";
bool test4 = Invert<1 < 1>::result;
std::cout << "test4 " << test4 << "\n";
bool test5 = Invert<1 > 1>::result;//error error: expected primary-expression before numeric constant
std::cout << "test5 " << test5 << "\n";
return 0;
}
在第 22 行出现错误
main.cpp:在函数“int main()”中:main.cpp:22:26:错误:预期 数值常量之前的主要表达式 bool test5 = Invert 1>::结果;
如果我评论这些行,它会完美运行 Working example with commented error line
解决方案后添加问题
因为我从 cmets 了解到是因为解析
但是为什么我在bool test4 = Invert<1 < 1>::result; 中没有遇到问题,这次解析器怎么聪明
【问题讨论】:
-
好吧,
Invert<1 >是什么? -
它认为第一个 > 正在关闭模板参数列表,将其括在括号中
-
只需将
<1 > 1>替换为<(1 > 1)>。 -
括号是你的朋友:
Invert<1 > 1>->Invert<(1 > 1)> -
离题问题。任何人都知道如何更改问题标题,因为它没有反映确切的问题。因为它与模板解析更相关
标签: c++