Perfect forwarding with variadic template function

I think what I'm trying to do is called perfect forwarding but I can't get it to work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

void bar(int&) {std::cout << "int&" << std::endl;}
void bar(const int&) {std::cout << "const int&" << std::endl;}
void bar(int&&) {std::cout << "int&&" << std::endl;}

template <typename... Args>
void foo(Args&&... args)
{
	return bar(args...);
}

int main()
{
	int i = 0;
	const int ci = 0;
	
	foo(i);
	foo(ci);
	foo(5);
}
int&
const in&
int&


I want the result to be the same as when I call bar directly.
1
2
3
bar(i);
bar(ci);
bar(5);
int&
const in&
int&&


What am I doing wrong?
Inside your void foo(), each arg is an lvalue. You need to use std::forward to turn it back into rvalue if it needs to be one

http://en.cppreference.com/w/cpp/utility/forward

example: http://ideone.com/AxBD0
Last edited on
Thank you that works perfect.
Topic archived. No new replies allowed.