2010-08-13 70 views
0

我編譯以下問題的模板專業化的派生類

#include <iostream> 

#define XXX 1 
#define YYY 2 

class X 
{ 
public: 

    template< int FLD > 
    void func(); 
}; 

template<> void X::func<XXX>() 
{ 
    std::cout << "X::func< " << XXX << " >" << std::endl; 
} 

class Y : public X 
{ 
public: 
}; 

template<> void Y::func<YYY>() 
{ 
    std::cout << "Y::func< " << YYY << " >" << std::endl; 
} 

template<> void Y::func<XXX>() 
{ 
    std::cout << "Y::func< " << XXX << " >" << std::endl; 
} 

int main(int c, char *v[]) 
{ 
    X x; 

    Y y; 
} 

我得到

x.cpp:24: error: template-id 'func<2>' for 'void Y::func()' does not match any template declaration 
x.cpp:24: error: invalid function declaration 
x.cpp:29: error: template-id 'func<1>' for 'void Y::func()' does not match any template declaration 
x.cpp:29: error: invalid function declaration 

我想專注於一個基類的模板。

任何人都可以解釋它是如何完成的或爲什麼我不能這樣做。

Thx Mark。

回答

1

你不能這樣做,因爲你不能做以下任,爲相同的原因,Y::func未在Y中聲明:

class X { 
public: 
    void foo(); 
}; 
void X::foo() {} 
class Y : public X { 
}; 
void Y::foo() {} 
+0

Doh !!。我是多麼愚蠢的人...... – ScaryAardvark 2010-08-13 13:38:50

1

沒有與名稱func()的Y類中聲明沒有方法,所以編譯器無法找到任何Ÿ:: FUNC()聲明