2010-06-18 60 views
3

我想專門爲類C創建一個模板方法,它本身是由int參數模板化的 。模板專門化的C++編譯器錯誤

我該怎麼做?

template <int D=1> 
class C { 
    static std::string foo() { stringstream ss; ss << D << endl; return ss.str();}  
}; 

template <class X> 
void test() { cout << "This is a test" << endl;} 

template <> 
template <int D> 
void test<C<D> >() {cout << C<D>::foo() << endl;} 

test()的特化失敗,「void test()聲明中的模板參數列表太多」。

回答

2

功能模板部分專業化是不允許的。做

template <int D> 
void test() {cout << C<D>::foo() << endl;} 
1

您不希望第一個template<>對您的部分專業化test<C<D>>。此外,您只能部分專門化類模板,而不能使用功能模板。像這樣的東西可能會奏效:

template <class X> 
struct thing 
{ 
    static void test() { cout << "This is a test" << endl;} 
}; 

template <int D> 
struct thing<C<D>> 
{ 
    static void test() {cout << C<D>::foo() << endl;} 
}; 

如果你的函數模板了一個參數,並使用了推斷模板參數,那麼你可以使用重載得到類似的效果,是這樣的:

template <class X> 
void test(const X&) { cout << "This is a test" << endl;} 

template <int D> 
void test(const C<D>&) {cout << C<D>::foo() << endl;} 

test(3); // calls first version 
test(C<3>()); // calls second version 
+0

這是行不通的。現在我收到一條消息: 部分專業化'test >'不允許 – user231536 2010-06-18 15:32:21

+0

哦,是的,我已經忘記了這一點。你只能部分專門化類模板。 – 2010-06-18 15:38:58