C ++期望的主表达式错误 [英] C++ expected primary-expression error

查看:361
本文介绍了C ++期望的主表达式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用g ++编译下面的代码时,我得到了一个'int''之前的主表达式错误。你知道为什么和如何解决它吗?谢谢!

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


推荐答案

$ c> foo()函数,编译器不知道bar是成员模板。您必须告诉它:

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
}

编译器认为bar只是一个成员变量,你试图比较它与某些东西,例如 t.bar< 10 。因此,它会抱怨int不是一个表达式。

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.

这篇关于C ++期望的主表达式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆