2012-02-17 120 views
2

在C++中,我正在嘗試爲模板化對象專門化模板化函數。爲模板類專門化模板函數

這是一個基本的例子: test.h:

template <class T> 
class myC { 
    T x; 
}; 

template <class U> 
void f(U y) { 
} 

template <> 
template <class T> 
void f<myC<T> >(myC<T> y) { 
} 

TEST.CPP

#include "test.h" 
int main() { 
    myC<double> m; 
    f(m); 
} 

GCC 4.6.1使我有以下錯誤信息:

In file included from test.cpp:1:0: 
test.h:13:25: error: too many template parameter lists in declaration of ‘void f(myC<T>)’ 
test.h:13:6: error: template-id ‘f<myC<T> >’ for ‘void f(myC<T>)’ does not match any template declaration 
test.h:13:25: note: saw 2 ‘template<>’, need 1 for specializing a member function template 

這是可能嗎?還是有另一種方法來實現相同的目標?

回答

2

不能專門的模板功能;只有模板類可以是專門的。 編輯:Nawaz的回答是正確的:它是部分專業化,不允許用於模板功能,僅適用於類。一個完整的專業化是可能的:

template <class U> void f(U y) {} 
template<> void f<double>(double y) {} // specialization for double 

注意,模板參數不必明確指明,如果它可以從上下文推斷:

template<> void f<>(int y) {} // specialization for int 

在你的情況,充分專業化是不可能的,因爲函數參數是一個模板類。但是,像任何函數一樣,模板函數可以被重載。在你的情況下,它會是這樣的:

template <class T> 
class myC { 
    T x; 
}; 

template <class U> 
void f(U y) { 
} 

template <class T> 
void f(myC<T> y) { 
} 

int main() { 
    myC<double> m; 
    f(m); 
    return 0; 
} 
0

據我所知,你不能專門化模板功能,只能模板類(或結構)。

但是,這是很難的限制:只需要聲明靜態公共成員函數的結構和MAVE模板參數的結構:

template <class T> 
class myC { 
    T x; 
}; 

template <class U> 
struct Foo 
{ 
    static void f(U y) { 
    } 
}; 

template <> 
template <class T> 
struct Foo<myC<T> > 
{ 
    static void f(myC<T> y) { 
    } 
}; 

的缺點是,類模板不會自動解決模板參數。但是,可以用函數模板easlily解決,類似於原始之一:

template <class U> 
void f(U y) { 
    return Foo<U>::f(y); 
} 
4
template <> 
template <class T> 
void f<myC<T> >(myC<T> y) { 
} 

什麼你atttempting在這裏做的是叫做部分專業化未在功能允許的情況下,模板。

功能模板是完全專門的,或根本不專門。語言規範不允許功能模板的部分專業化。

這樣你就可以超載函數模板爲:

template <class T> 
void f(myC<T> y) //note that it is overload, not specialization 
{ 
} 

這是允許的,並且優於模板甚至完全專業化。

閱讀香草薩特這些文章:

+0

是不是它在C++ 11中引入? – 2012-02-17 19:51:54