Last updated:2026-10-12
C++17 Template auto Deduction¶
Everything in C++ can be auto¶
C++17 introduced many features aimed at making code more expressive and reducing template boilerplate. One notable enhancement is the ability to declare non-type template parameters with the auto keyword. In certain scenarios this feature is particularly convenient, because it removes the need for explicit type declarations. Below I will introduce how I used this feature at work, that is, in a database!
Learning from practice: the complete source code of this section will be uploaded to the members' community; see the QR code at the end of the page if you are interested.
Using auto for non-type template parameters in C++17¶
Sorting in a database scenario¶
Consider a database-related class Foo that you want to sort according to a specific order represented by an enum:
You have Foo instances with different sort orders:
The previous way of implementing it¶
Before C++17, we might have implemented it like this:
However, this can cause errors, because the compiler cannot infer the template parameter 'U'.
The simplified way now¶
Since C++17, for non-type template parameters we can use the auto keyword instead:
This approach is simpler, letting us use non-type template parameters without explicitly specifying the type.
Simplifying integral_constant¶
Previously, we might have implemented integral_constant in the following way:
And now all we need is:
This simplification makes the code clearer and easier to read.
Conclusion¶
The use of the auto keyword for declaring non-type template parameters introduced in C++17 greatly simplifies template code. By eliminating tedious type declarations, we can express the intent of the code more directly, improving its readability and maintainability. When dealing with scenarios such as sorting, this feature is especially useful, letting us focus on the essence of the problem rather than the details of template parameters.
Related Topics¶
- C++17 [[nodiscard]] Attribute | C++那些事
- C++17 std::string_view | C++那些事
- C++17 PMR Memory Resources | C++那些事
- C++17 Seventeen Advanced Features | C++那些事
- C++17 Class Template Argument Deduction CTAD | C++那些事
- C++17 optional_ref | C++那些事
- C++17 std::variant | C++那些事
- C++17 Structured Bindings | C++那些事
- C++17 Variable Templates | C++那些事