I simply would print out a non type template parameter pack. But I can't find a valid expansion if I want to have spaces in between the elements.
Example:
template < int ... N >
struct X
{
static void Check() {
// this will become std::cout << ( 1 << 2 ) << std::endl; -> prints "4"
std::cout << "X" << (N << ...) << std::endl;
// this will become: ((std::cout << 1 ) << 2 ) << std::endl; -> prints "12"
(std::cout << ... << N) << std::endl;
// this becomes: (( std::cout << " " << 1 ) << 2 ) -> prints " 12"
(std::cout << " " << ... << N) << std::endl;
// the following is not allowed
(std::cout << ... << " " << N) << std::endl;
// also this one is not compiling
(std::cout << ... << N << " ") << std::endl;
}
};
int main()
{
X<1,2>::Check();
}
Is there any chance to expand the parameter pack to print the elements with space in between without using a helper function?
Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.
A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.
Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.
With the use of a helper variable.
std::size_t count{};
((std::cout << (count++? " " : "") << N), ...);
Another alternative is to additionally define the first template parameter to facilitate formatting.
#include <iostream>
template<int... N>
struct X {
static void Check() {
if constexpr (sizeof...(N))
[](auto first, auto... rest) {
std::cout << first;
((std::cout << " " << rest), ...);
std::cout << "\n";
}(N...);
}
};
int main() {
X<1,2>::Check();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With