Naming template parameters is an important aspect of writing clear and maintainable C++ code. While there aren't strict rules, there are some conventions that may be worth considering:
For simple, general-purpose templates, it's common to use single uppercase letters. For example:
T
for a general typeN
for a compile-time integral valueE
for element type in containerstemplate <typename T, std::size_t N>
class Array {
T elements[N];
};
For more complex templates or when the purpose of the parameter is not immediately obvious, use more descriptive names:
#include <memory> // For std::allocator
template <
typename ElementType,
typename Allocator = std::allocator<ElementType>
>
class MyVector {
// ...
};
T
for type parameters: TKey
, TValue
N
for non-type parameters: NSize
, NAlignment
#include <cstddef> // For std::size_t
template <
typename TKey,
typename TValue, std::size_t NMaxSize
>
class FixedMap {
// ...
};
It’s common to use PascalCase for type parameters and camelCase for non-type parameters:
#include <cstddef> // For std::size_t
template <
typename InputIterator,
typename OutputIterator,
std::size_t bufferSize
>
void CopyWithBuffer(
InputIterator first,
InputIterator last,
OutputIterator result) {
// ...
}
If your template is similar to something in the standard library, consider using similar naming conventions:
#include <utility> // For std::less
template <
typename Key,
typename T,
typename Compare = std::less<Key>
>
class MyOrderedMap {
// ...
};
typename
Instead of class
While both typename
and class
are allowed, typename
is generally preferred as it's more accurate (not all types are classes):
template <typename T>
class MyTemplate {
// ...
};
Remember, the goal is to make your code as readable and self-explanatory as possible. Choose names that convey the purpose or constraints of the parameter. If a single letter suffices, use it. If more context is needed, don't hesitate to use a longer, more descriptive name.
Lastly, be consistent within your codebase or team. If your team has established naming conventions, follow those even if they differ slightly from these general guidelines.
Answers to questions are automatically generated and may not have been reviewed.
Learn how templates can be used to create multiple classes from a single blueprint