2012-02-15 172 views
9

可能重複:
Where and why do I have to put the 「template」 and 「typename」 keywords?調用模板函數

下面的代碼:

template<typename T> 
class base 
{ 
public: 
    virtual ~base(); 

    template<typename F> 
    void foo() 
    { 
     std::cout << "base::foo<F>()" << std::endl; 
    } 
}; 

template<typename T> 
class derived : public base<T> 
{ 
public: 
    void bar() 
    { 
     this->foo<int>(); // Compile error 
    } 
}; 

而且,在運行時:

derived<bool> d; 
d.bar(); 

我收到以下錯誤:

error: expected primary-expression before ‘int’ 
error: expected ‘;’ before ‘int’ 

我所知道的non-dependent names and 2-phase look-ups。但是,當函數本身是一個模板函數(我的代碼中的foo<>()函數)時,我嘗試所有解決方法只是失敗。

回答

19

foo是一個從屬名稱,所以第一階段查找假定它是一個除非您使用typenametemplate關鍵字來指定,否則可變。在這種情況下,你想:

this->template foo<int>(); 

this question如果你想的複雜細節。

+0

謝謝!今天真的救了我的培根 – Jacko 2013-12-19 16:09:58

7

你應該做的是這樣的:

template<typename T> 
class derived : public base<T> 
{ 
public: 
    void bar() 
    { 
     base<T>::template foo<int>(); 
    } 
}; 

這裏充滿編譯例如:

#include <iostream> 

template<typename T> 
class base 
{ 
public: 
    virtual ~base(){} 

    template<typename F> 
    void foo() 
    { 
     std::cout << "base::foo<F>()" << std::endl; 
    } 
}; 

template<typename T> 
class derived : public base<T> 
{ 
public: 

    void bar() 
    { 
     base<T>::template foo<int>(); // Compile error 
    } 
}; 

int main() 
{ 
    derived<int> a; 
    a.bar(); 
}