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

Contenido del Curso

C++ Templates

C++ Templates

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

bookIntroduction 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?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt