Here is my first code in variadic templates :
void print_f()
{
}
template<typename T, typename ... ARG>
void print_f(const T& a, ARG... C)
{
std::cout<<a;
print_f(C...); // -> at this line I want to know
std::cout<<std::endl;
}
when I make a recursive call to print_f(C...); , what actually happens? what I mean is
template parameter pack C gets unpacked and how is function argument deduction is done in variadic templates , how is matching done?
can anyone please explain some basics?
Edit: Usually in template class like
template <typename T> class x{
public:
T aa; // can declare variable of type T
};
but in variadic templates :
template<typename T, typename ... ARG>
void print_f(const T& a /* , ARG... C -> if remove this */ )
{
std::cout<<a;
ARG... C // and put it here , we can't do this, why?
print_f(C...);
std::cout<<std::endl;
}
I think your first printf overload must also be a template, but I’m not 100% sure.
Anyway, it works more or less like this:
It should also be noted that with your code, all the values appear on the same line, followed by lots of blank lines. I think you wanted the
endlbefore the recursion.As per your edit: In your hypothetical function
template<typename T, typename ... ARG>, you would be unable to call this function unless you specified ARG yourself, as it cannot be deduced from the function parameter types, since ARG is no longer in the parameters.void print_f(const T& a)
Also, variadic templates cannot be instantiated because they are not a type, they are a grouping of types. If you really wanted to instantiate something, you could use a tuple:
std::tuple<ARGS> C;, but all the objects would be default constructed, since you didn’t pass parameters to the function to construct from.