2015-04-16 137 views
2

我正在努力解決編譯問題。給定一個基於T的模板,它包含一個用U模板化的方法,我不能從派生類中調用該方法。下面的示例重現我的問題:C++模板類繼承與其他模板方法

#include <iostream> 
#include <vector> 

template <class T> 
class Base 
{ 
protected: 
    template <class U> 
    std::vector<U> baseMethod() const 
    { 
    return std::vector<U>(42); 
    } 
}; 

template <class T> 
class Derived : public Base<T> 
{ 
public: 
    std::vector<int> derivedMethod() const 
    { 
    return baseMethod<int>(); 
    } 
}; 

int main() 
{ 
    Derived<double> d; 
    std::vector<int> res = d.derivedMethod(); 
    return 0; 
} 

編譯結果:

t.cc:21:12: error: ‘baseMethod’ was not declared in this scope 
t.cc:21:23: error: expected primary-expression before ‘int’ 
t.cc:21:23: error: expected ‘;’ before ‘int’ 
t.cc:21:26: error: expected unqualified-id before ‘>’ token 

回答

2

您應該添加template關鍵字對待baseMethoddependent template名稱:

std::vector<int> derivedMethod() const 
{ 
    return this->template baseMethod<int>(); 
} 

在模板中定義,除非消歧k,否則不屬於當前實例化的依賴名稱不被視爲模板名稱使用eyword template(或除非它已經建立爲模板名稱)。

欲瞭解更多詳情:Where and why do I have to put the "template" and "typename" keywords?

+0

哇,非常感謝! – crep4ever