How it works...

Before C++17, you could provide non-type template arguments in a template, but you had to state the variable type in the definition, as shown in this example:

#include <iostream>

template<int answer>
void foo()
{
std::cout << "The answer is: " << answer << ' ';
}

int main(void)
{
foo<42>();
return 0;
}

The output is as follows:

In the preceding example, we create a template argument variable of the int type and output the value of this variable to stdout. In C++17, we can now do the following:

#include <iostream>

template<auto answer>
void foo()
{
std::cout << "The answer is: " << answer << ' ';
}

int main(void)
{
foo<42>();
return 0;
}

The output is as follows:

As shown in the preceding, instead of having to state int, we can now state auto. This allows us to create a single function that can take more than one non-type template parameter. We can also use type traits to establish which non-type parameters are allowed, as shown in this example:

#include <iostream>
#include <type_traits>

template<
auto answer,
std::enable_if_t<std::is_integral_v<decltype(answer)>, int> = 0
>
void foo()
{
std::cout << "The answer is: " << answer << ' ';
}

int main(void)
{
foo<42>();
return 0;
}

The output is as follows:

In the preceding example, our template non-type parameter can only be an integer type.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset