Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
193 views
Welcome To Ask or Share your Answers For Others

1 Answer

template <typename T>
void g(T&& t) {
  f(std::forward<T>(t).x);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...