Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfect forwarding a member of object

Suppose I have two structs:

struct X {};
struct Y { X x; }

I have functions:

void f(X&);
void f(X&&);

How do I write a function g() that takes Y& or Y&& but perfect forwarding X& or X&& to f(), respectively:

template <typename T>
void g(T&& t) {
  if (is_lvalue_reference<T>::value) {
    f(t.x);
  } else {
    f(move(t.x));
  }
}

The above code illustrate my intention but is not very scalable as the number of parameters grows. Is there a way make it work for perfect forwarding and make it scalable?

like image 809
Kan Li Avatar asked Dec 20 '11 04:12

Kan Li


1 Answers

template <typename T>
void g(T&& t) {
  f(std::forward<T>(t).x);
}
like image 157
Johannes Schaub - litb Avatar answered Oct 15 '22 19:10

Johannes Schaub - litb