Best Practices for Naming Template Parameters
What are the best practices for naming template parameters?
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:
Single-Letter Names for Simple Cases
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 containers
template <typename T, std::size_t N>
class Array {
T elements[N];
};
Descriptive Names for Complex Cases
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 {
// ...
};
Prefixes for Different Kinds of Parameters
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 {
// ...
};
Casing
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) {
// ...
}
Consistency with the Standard Library
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 {
// ...
};
Use 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.
Class Templates
Learn how templates can be used to create multiple classes from a single blueprint