Write print function to print all arugments

I want to make a function to print all arguments (maybe of a different type ) how can i make -

template <typename T>
void print(T x){cout<<x<<endl;}
template <typename T1, typename T2>
void print(T1 x,T2 y){cout<<x<<" "<<y<<endl;}
template <typename T1, typename T2,typename T3>
void print(T1 x, T2 y,T3 z){cout<<x<<" "<<y<<" "<<z<<endl;}

now I make 3 functions same name different number of arguments, but let say I call print function with 5 parameters now it will give me an error (as no definition with 5 parameters) , but now i wanna make a function which accepts any number of parameters (not array or vector only int , string double etc) and print them with space

@ssjgz

#include <iostream>

using namespace std;

template <typename Head>
void print(Head&& head)
{
    cout << head << endl;
}

template <typename Head, typename... Tail>
void print(Head&& head, Tail... tail)
{
    cout << head << " ";
    print(tail...);
}

int main()
{
    string sausage = "sausage";
    print(sausage, 5, 7.7);
}
4 Likes

Can you tell us what the Double address operator does? All I could find is something about l and r values, which is not very informative as to what the && operator actually does.

Is this particular case, they denote forwarding references:

https://en.cppreference.com/w/cpp/language/reference#Forwarding_references

though I’ve not really used them as such, here (i.e. I don’t use them in conjunction with std::forward), as I don’t think there are any situations where it makes a difference(?) in this case.

Now that I come to think of it, you could probably actually simplify everything above down to just:

#include <iostream>

using namespace std;

void print()
{
    cout << endl;
}

template <typename Head, typename... Tail>
void print(const Head& head, const Tail&... tail)
{
    cout << head << " ";
    print(tail...);
}

int main()
{
    string sausage = "sausage";
    print(sausage, 5, 7.7);
    cout << boolalpha;
    print("pickles", 100.778, true);
}
3 Likes