【问题标题】:Expected primary-expression before numeric constant数字常量之前的预期主表达式
【发布时间】: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&lt;1 &lt; 1&gt;::result; 中没有遇到问题,这次解析器怎么聪明

【问题讨论】:

  • 好吧,Invert&lt;1 &gt; 是什么?
  • 它认为第一个 > 正在关闭模板参数列表,将其括在括号中
  • 只需将&lt;1 &gt; 1&gt; 替换为&lt;(1 &gt; 1)&gt;
  • 括号是你的朋友:Invert&lt;1 &gt; 1&gt; -> Invert&lt;(1 &gt; 1)&gt;
  • 离题问题。任何人都知道如何更改问题标题,因为它没有反映确切的问题。因为它与模板解析更相关

标签: c++


【解决方案1】:

要允许正确解析,您必须使用括号:

bool test5 = Invert<(1 > 1)>::result;

【讨论】:

  • bool test4 = Invert::result; 没有问题在这种情况下如何确定解析
  • @HariomSingh - 因为已经看到了模板的左括号。它不像是期待另一个,尼特?
  • 解析器从左到右扫描事物。如果它看到Invert&lt;1&gt;,它认为它看到了一个完整的模板,但如果它看到Invert&lt;1&lt;,它不可能将它解释为一个完整的模板。
猜你喜欢
  • 2016-07-26
  • 1970-01-01
  • 2020-01-16
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
相关资源
最近更新 更多