2011-11-28 57 views

回答

12

发表在其他问题:

template <class T> 
struct foo : T { 
    void bar() { 
    x = 5;  // doesn't work 
    this->x = 5; // works - T has a member named x 
    } 
}; 

没有this->编译器不知道x是(继承)成员。

类似使用的typenametemplate模板代码里面:

template <class T, class S> 
struct foo : T { 
    typedef T::ttype<S>; // doesn't work 
    typedef typename T::template ttype<S> footype; // works 
}; 

这是愚蠢的,有点多余,但你仍然必须这样做。

+0

好的,谢谢你的回答:)现在停止发布关于这个问题的另一个问题... typename T :: template ttype - 为什么你需要::模板这一行? –

+0

@ w00te有一个[优秀的FAQ条目](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords)这解释何时何地使用'typename'和'template' – Praetorian

+0

感谢Praetorian - 我会检查出来:) –

5
template <typename T> 
struct Base 
{ 
    void foo() {} 
}; 

template <typename T> 
struct Derived : Base<T> 
{ 
    void bar() 
    { 
    // foo(); //foo() is a dependent name, should not call it like this 
    // Base<T>::foo(); //This is valid, but prevents dynamic dispatch if foo is virtual 
    this->foo(); //use of this-> forces foo to be evaluated as a dependent name 
    } 
}; 

更详细的解释可以在C++ FAQ

+0

+1“_dynamic dispatch_” – curiousguy