Core C++, 5 of N: Explicit and Partial Specialization -- Stephan T. Lavavej
Stephan T. Lavavej, aka STL, will take us on a journey of discovery within the exciting world of Core C++. We know lots of folks are either coming back to C++, coming to C++, or have never left C++. This lecture series, in n parts, is for all of you! Only STL can make that work (novice, intermediate, and advanced all bundled together and presented in a way only STL can do).
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 <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(); }
Add a Comment
Comments are closed.