我已經通過VS2010運行以下代碼。爲什麼實現順序在「爲什麼不專用功能模板」中很重要
#include <iostream>
template<class T> // (a) a base template
void f(T)
{ std::cout << "(a)" << std::endll;}
template<class T> // (b) a second base template, overloads (a)
void f(T*) // (function templates can't be partially
{ std::cout << "(b)" << std::endll;}
template<> // (c) explicit specialization of (b)
void f<>(int*)
{ std::cout << "(c)" << std::endll;}
int main(int argc, char* argv[])
{
int *p = new int(10);
f(p); // '(c)'
return 0;
}
/////////////////
#include <iostream>
template<class T> // (a) same old base template as before
void f(T)
{ std::cout << "(a)" << std::endll;}
template<> // (c) explicit specialization, this time of (a)
void f<>(int*)
{ std::cout << "(c)" << std::endll;}
template<class T> // (b) a second base template, overloads (a)
void f(T*)
{ std::cout << "(b)" << std::endll;}
int main(int argc, char* argv[])
{
int *p = new int(10);
f(p); // '(b)'
return 0;
}
輸出結果是(c)
。然而,如果我將(c)代碼塊移到(b)之前,那麼輸出結果是(b)
。 我已閱讀相關文章http://www.gotw.ca/publications/mill17.htm這裏。仍然感到困惑。
爲什麼在這種情況下代碼的順序很重要?
在第二種情況下,你爲什麼認爲'(c)'是'(b)'的一個專長?如果是這樣,那麼在主模板之前專業化怎麼樣? – Nawaz 2012-08-16 15:07:16
無論如何,PS應該是'template <> void f(int *)'。我有一個懷疑,你有一個普通的不合格的程序。 –
2012-08-16 15:08:23
@Nawaz,這不是我的評論,它來自香草Sutter – q0987 2012-08-16 16:01:10