开发者

C++ expected primary-expression error

开发者 https://www.devze.com 2023-02-08 08:55 出处:网络
I got a \'expected primary-expres开发者_JAVA百科sion before \'int\'\' error when compiling with g++ the following code. Do you know why and how to fix it ? Thank you !

I got a 'expected primary-expres开发者_JAVA百科sion 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, e.g. t.bar < 10. As a result, it complains that "int" is not an expression.

0

精彩评论

暂无评论...
验证码 换一张
取 消