Conteúdo do Curso
C++ Templates
C++ Templates
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.
main
#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.
main
#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.
Obrigado pelo seu feedback!