類別樣板的明確特製化
類別樣板可以專門針對特定的型別或樣板引數的值。 特製化可讓您能夠自訂特定的引數型別或值的樣板程式碼。 特製化,而相同的程式碼會產生每個型別用於樣板執行個體化。 特製化,在特定的型別使用時,定義之特製化做代替原始範本定義。 特製化都有相同的名稱都是特製化的樣板。 然而,樣板特製化可以從原始範本的多種方式不同。 比方說,它可以具有不同的資料成員和成員函式。
使用特製化來自訂特定類型或值的範本。 當範本都有一個以上的樣板引數,且您只需要特殊化其中一個圖形,或您想要特製化型別,例如所有指標型別、 參考型別或陣列型別的一整組的行為,請使用部分特製化。 如需詳細資訊,請參閱的類別樣板部分特製化。
範例
// explicit_specialization1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
// Template class declaration and definition
template <class T> class Formatter
{
T* m_t;
public:
Formatter(T* t) : m_t(t) { }
void print()
{
cout << *m_t << endl;
}
};
// Specialization of template class for type char*
template<> class Formatter<char*>
{
char** m_t;
public:
Formatter(char** t) : m_t(t) { }
void print()
{
cout << "Char value: " << **m_t << endl;
}
};
int main()
{
int i = 157;
// Use the generic template with int as the argument.
Formatter<int>* formatter1 = new Formatter<int>(&i);
char str[10] = "string1";
char* str1 = str;
// Use the specialized template.
Formatter<char*>* formatter2 = new Formatter<char*>(&str1);
formatter1->print();
formatter2->print();
}