Skip to content

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:

enum class SortOrder { Ascending, Descending };

You have Foo instances with different sort orders:

Foo<SortOrder::Ascending> f1;
Foo<SortOrder::Descending> f2;

The previous way of implementing it

Before C++17, we might have implemented it like this:

template <typename U, template <U> class T, U K>
auto GetSortOrder(const T<K>&) {
  return K;
}

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:

template <template <auto> class T, auto K>
auto GetSortOrder(const T<K>&) {
  return K;
}

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:

template <typename _Tp, _Tp __v>
struct integral_constant {}

And now all we need is:

template <auto __v>
struct integral_constant {}

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.

Comments