user511274
user511274

Reputation: 513

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);
 }

Upvotes: 3

Views: 1465

Answers (1)

Sjoerd
Sjoerd

Reputation: 6875

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, e.g. t.bar < 10. As a result, it complains that "int" is not an expression.

Upvotes: 14

Related Questions