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

Course Content

C++ Templates

C++ Templates

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

bookNaming 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.

cpp

main

copy
1234
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.

cpp

main

copy
1234
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.

cpp

main

copy
12345
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.

What Could Fit in the Placeholders?

What Could Fit in the Placeholders?

Select a few correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 5
some-alt