Compartilhar via


Explicit Specialization of Class Templates

Class templates can be specialized for specific types or values of the template arguments. Specialization allows template code to be customized for a specific argument type or value. Without specialization, the same code is generated for each type used in a template instantiation. In a specialization, when the specific types are used, the definition for the specialization is used instead of the original template definition. A specialization has the same name as the template of which it is a specialization. However, a template specialization can be different in many ways from the original template. For example, it can have different data members and member functions.

Use specialization to customize a template for a specific type or value. Use partial specialization when the template has more than one template argument and you only need to specialize one of them, or when you want to specialize behavior for an entire set of types, such as all pointer types, reference types, or array types. For more information, see Partial Specialization of Class Templates.

Example

// 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(&i);

    char str[10] = "string1";
    char* str1 = str;
    // Use the specialized template.
    Formatter<char*> formatter2(&str1);

    formatter1.print(); // 157
    formatter2.print(); // Char value : s
}
157
Char value: s

See Also

Reference

Class Template Instantiation

Partial Specialization of Class Templates (C++)