2016-01-21 41 views
0

我试图理解为什么(使用gcc 4.8.2)以下代码不能编译:调用模板函数成员时,它的名字叫同一个名字

struct A { 
    template <typename T> 
    T f() {return T(0);} 
}; 

struct B : A { 
    using MyT = int; 
    MyT f() {return (A *)this->template f<MyT>();} 
}; 

int main() 
{ 
    B b; 
    std::cout << b.f() << std::endl; 
    return 0; 
} 

如果我改变从f名称在基地f1,那么下面编译就好:

struct A { 
    template <typename T> 
    T f1() {return T(0);} 
}; 

struct B : A { 
    using MyT = int; 
    MyT f() {return this->template f1<MyT>();} 
}; 
+0

运算符优先级。 –

+0

要扩展@ T.C.的评论:'return static_cast (this) - > template f ();' –

回答

3

只是因为运营商precendence,你是铸造f功能的结果A*,而不是投thisA*,实际上使用static_cast更好。

MyT f() {return static_cast<A*>(this)->f<MyT>();} 

这将工作。并且您还隐藏名称,您只需执行以下操作:

struct B : A { 
    using MyT = int; 
    using A::f; 
    MyT f() {return this->f<MyT>();} 
}; 
+0

谢谢!在最后一部分中,即使没有'this->'也可以工作。 – AlwaysLearning

+0

嗯...第二个建议不适用于我的实际代码。调用'static_cast (this) - > template后继者()'可以工作,但调用'后继者()'不会有'使用Base ::后继者'... – AlwaysLearning

相关问题