简体   繁体   中英

C++ expected primary-expression error

I got a 'expected primary-expression before 'int'' error when compiling with g++ the following code. 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 . 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 . As a result, it complains that "int" is not an expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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