Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to Template Specialization | Template Specialization
C++ Templates
course content

Course Content

C++ Templates

C++ Templates

1. Creating First Template
2. Templates Usage
3. Class Templates
4. Template Specialization

book
Introduction to Template Specialization

A general template works for any data type. However, certain types might require special treatment. For example, if you're implementing a function that behaves differently for int and std::string types, template specialization allows you to define a different version of the template for each type.

cpp

main

copy
123456789101112
#include <iostream> template<typename T> T square(T value) { return value * value; } int main() { std::cout << square<int>(25); std::cout << square<std::string>("5"); }

If you run the code above, you will encounter an error. This occurs because std::string does not support the * operator. Therefore, it is necessary to inform the compiler about how to handle a std::string passed as a parameter.

How Templates Work Under the Hood

For now, you are just grasping the basics of templates, specifically function templates. You have learned how to create them, use parameter lists, and call the functions with different data types. You might wonder why, in this case, we wouldn't just overload functions for all available numeric types in C++. While this approach could work for this example, it’s important to remember that templates are a much more powerful tool.

cpp

main

copy
12345678910111213
#include <iostream> struct myStruct {}; class myClass {}; template<typename T> void TemplateFunction() { std::cout << typeid(T).name() << std::endl; } int main() { TemplateFunction<myClass>(); TemplateFunction<myStruct>(); }

Templates can accept any data type, including user-defined types. In contrast, relying solely on function overloading would require creating a new function for each type, making updates cumbersome and error prone. Therefore, we can't rely on function overloading alone and must use template specializations to address issues like those in the square template function.

Why does the square function template in the example produce an error when std::string is used?

Why does the square function template in the example produce an error when std::string is used?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 1
We're sorry to hear that something went wrong. What happened?
some-alt