简体   繁体   English

C ++期望的主表达式错误

[英]C++ expected primary-expression error

I got a 'expected primary-expression before 'int'' error when compiling with g++ the following code. 当使用g ++编译以下代码时,我在'int''错误之前得到了'预期的primary-expression'。 Do you know why and how to fix it ? 你知道为什么以及如何解决它吗? Thank you ! 谢谢 !

 struct A
 {
     template <typename T>
     T bar() { T t; return t;}
 };

 struct B : A
 {
 };

 template <typename T>
 void foo(T  & t)
 {
     t.bar<int>();
 }

 int main()
 {
     B b;
     foo(b);
 }

When compiling the foo() function, the compiler doesn't know that bar is a member template . 编译foo()函数时,编译器不知道bar是成员模板 You have to tell it that: 你必须告诉它:

template <typename T>
void foo(T & t)
{
  t. template bar<int>(); // I hope I put template in the right position
}

The compiler thinks that bar is just a member variable, and that you try to compare it with something, eg t.bar < 10 . 编译器认为bar只是一个成员变量,并且您尝试将其与某些内容进行比较,例如t.bar < 10 As a result, it complains that "int" is not an expression. 结果,它抱怨“int”不是表达。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM