Episode

Stephan T. Lavavej - Core C++, 5 of n

In Part 5, Stephan teaches us about Explicit and Partial Specialization of class and function templates.

From MSDN ->

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.

// explicit_specialization1.cpp // compile with: /EHsc #include using namespace std;

// Template class declaration and definition template 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* formatter1 = new Formatter(&i);

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

formatter1->print(); formatter2->print(); }

See part 1: Name Lookup
See part 2: Template Argument Deduction See part 3: Overload Resolution See part 4: Virtual Functions