Contenido del Curso
C++ Templates
C++ Templates
Naming Conventions
Good and bad namings
Just like variables, you can name template parameters anything you want. However, adhering to naming conventions can greatly enhance code readability and maintainability. Here are some good and bad practices to consider.
main
template<typename T> // <- Actually a good naming void myTemplate() { // Function implementation }
You might wonder why T
is considered a better naming choice than Type
, even though the latter seems clearer. The reason is simple T
is a widely accepted convention that stands for Type. It immediately indicates that the template parameter represents a type, which is familiar to most developers. It is also common to use U
or V
if T
has already been used.
Descriptive naming
When you have multiple template parameters, and their purpose isn't immediately obvious, it's a good practice to use descriptive names prefixed with T
.
main
template<typename TKey, typename TValue> void map() { // Function implementation }
If you look at the documentation for some templates, you might notice that some developers add an underscore (_
) before the type parameter to make it more distinct. You can adopt this practice as well. However, the most important aspect is to maintain consistency throughout your codebase. Choose a naming style that you prefer and stick to it.
Class and typename
Both class
and typename
are used in template declarations. They are interchangeable in this context.
main
template <class T> void first_template(T param) { /* ... */ } template <typename T> void second_template(T param) { /* ... */ }
Historically, the class
keyword was the only option available for defining template parameters. As a result, you may encounter this keyword in older code. However, when creating templates, the typename
keyword is often preferred for its clarity so we will be using it.
¡Gracias por tus comentarios!