2011-02-02 76 views
3

当使用g ++编译下面的代码时,我在'int''错误之前得到'期望的主表达式'。你知道为什么以及如何解决它吗?谢谢 !C++预期的主表达式错误

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

难道是t.bar 这条线给你的错误吗? – reese 2011-02-02 19:59:25

回答

14

当编译foo()函数,编译器不知道酒吧是一个成员模板。你必须告诉它:

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

编译器认为酒吧只是一个成员变量,并尝试将它与一些东西,例如比较t.bar < 10。因此,它抱怨“int”不是表达式。

+0

+1:我不知道。 – 2011-02-02 20:04:16

相关问题