This example uses a common variadic template and function. I want to print out the arguments passed to f:
#include
template <
Since the question is general and in C++17 you can do it better, I would like to give two approaches.
Using fold expression, this could be simply
#include
#include // std::forward
template
constexpr void print(Args&&... args) noexcept
{
((std::cout << std::forward(args) << " "), ...);
}
int main()
{
print("foo", 10, 20.8, 'c', 4.04f);
}
output:
foo 10 20.8 c 4.04
(See Live Online)
With the help of if constexpr, now we can avoid providing base case/ 0-argument case to recursive variadic template function. This is because the compiler discards the false statement in the if constexpr at compile time.
#include
#include // std::forward
template
constexpr void print(T&& first, Ts&&... rest) noexcept
{
if constexpr (sizeof...(Ts) == 0)
{
std::cout << first; // for only 1-arguments
}
else
{
std::cout << first << " "; // print the 1 argument
print(std::forward(rest)...); // pass the rest further
}
}
int main()
{
print("foo", 10, 20.8, 'c', 4.04f);
}
output
foo 10 20.8 c 4.04
(See Live Online)