2011-10-24 89 views
1
template <class T> 
class Test{ 

public: 
    Test(T){ } 

    template <class U> 
    U to() const{ return U(0); } 
}; 


template <class Real> 
class Base{ 

    typedef Test<Real> TST; 

protected: 
    Base(const TST& t){ 

    _i = t.to<int>(); // <- but this gives error 
    } 

    int _i; 
}; 


template <class Real, class T> class Child; 

template <class Real> 
class Child<Real, int> : public Base<Real>{ 

    typedef Base<Real> F; 
    typedef Test<Real> TST; 

public: 
    Child() : F(TST(23.0)){ } 
}; 



int main(int argc, char* argv[]){ 

    Child<double, int> rw; 

    Test<double> t1(3.3); 
    int i = t1.to<int>(); // <- this works 

    return 0; 
} 

在主要作品中調用to,但我不明白爲什麼它不會在Base()中調用。我得到的錯誤是:爲什麼調用模板成員函數會出錯?

t1.cpp: In constructor ‘Base<Real>::Base(const TST&)’: 
t1.cpp:20:15: error: expected primary-expression before ‘int’ 
t1.cpp:20:15: error: expected ‘;’ before ‘int’ 

回答

4

因爲tTest<Real>型,其中Real是一個模板參數的,所以t的類型實際上是一個依賴型。你需要讓編譯器知道to是一個模板函數使用:

_i = t.template to<int>(); 

否則,你可以嘗試的t成員稱爲to(導致一些錯誤),這是編譯器假定什麼上使用的operator<除非您將其標記爲template。當從main調用時,t1的類型是Test<double>,它不依賴於任何模板參數,因此編譯器可以自行確定其模板函數。

+0

現在,它是一個靜態成員? –

+0

好的,靜態模板成員應該在模板結構或類名後面有'template'關鍵字:'Test :: template to(...)'。當然,從超自由的MSVC移植到G ++時,你只會開始考慮它。如果你喜歡在晚上睡覺,C++不適合你。 –

相關問題