Back
Close

7 Features of C++17 that will simplify your code

fenbf
100.1K views
Previous: Template argument deduction for class templates Next: Summary

Declaring non-type template parameters with auto

This is another part of the strategy to use auto everywhere. With C++11 and C++14 you can use it to automatically deduce variables or even return types, plus there are also generic lambdas. Now you can also use it for deducing non-type template parameters.

For example:

template <auto value> void f() { }

f<10>();               // deduces int

This is useful, as you don't have to have a separate parameter for the type of non-type parameter. Like:

template <typename Type, Type value> constexpr Type TConstant = value;
                // ^^^^                        ^^^^  
constexpr auto const MySuperConst = TConstant<int, 100>;

with C++17 it's a bit simpler:

template <auto value> constexpr auto TConstant = value;
                             // ^^^^
constexpr auto const MySuperConst = TConstant <100>;

So no need to write Type explicitly.

As one of the advanced uses a lot of papers/blogs/talks point to an example of Heterogeneous compile time list:

template <auto ... vs> struct HeterogenousValueList {};
using MyList = HeterogenousValueList<'a', 100, 'b'>;

Before C++17 it was not possible to declare such list directly, some wrapper class would have to be provided first.

More details in

MSVC not yet, GCC: 7.0, Clang: 4.0.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants