how create a Variadic Templates?

i have these Variadic Template:
1
2
3
4
5
6
7
8
9
10
11
12
template<typename T>
    static void write1(T t)
    {
        cout << t;
    }
template<typename... Args>
    static void write(Args...  args)
    {
        make_tuple( (write1(std::forward<Args>(args)), 0)... );
    }
//how use it:
write("hello world\n",10,"\nhello\n",20,30);

output:
3020
hello
10hello world

like we see the parameters are showed from right to left :(
can be fixed for show from left to right?
Last edited on
Wow, there is no need to make a simple "print" function so complicated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

void write() {} 

template<typename first_t, typename... rest_t>
void write(const first_t &first, const rest_t... rest)
{
	std::cout << first;
	write(rest...); //function is recursive
					//when the parameter pack becomes empty
					//write(); will be called with no parameters
					//which is why we declare it above
}

int main()
{
	write("hello world\n", 10, "\nhello\n", 20, 30);

	std::cin.get();
}
Last edited on
thanks for all.. it's working fine ;)
i'm sorry, but i'm confused: why the empty function?
The empty function is needed for the last recursive call.

Each time void write(const first_t &first, const rest_t... rest) is called it prints out the first argument and the rest of the arguments are stored in the const rest_t... rest parameter pack.

So then the function again is called with the parameter pack as an argument. So the parameter pack will expand into a const first_t &first and into another parameter pack and the first argument will be printed. In fact it will be the second. And so on and so forth.

In the end the parameter pack will become empty (after we have printed all the arguments). So what would happen if we call write(rest...); with an empty parameter pack? It's the same as calling write();. And since we don't have a function like that defined anywhere, without it, we would get a compilation error.

This is actually really difficult to explain just by writing. I hope I got through to somewhere :D
Last edited on
see these thing:
1
2
3
4
void write() {} 

template<typename first_t, typename... rest_t>
void write(const first_t &first, const rest_t... rest)

only the name is changed ;)
maybe i can build a nice macro for it ;)
Topic archived. No new replies allowed.