Perfect forwarding a member of object

北城余情 提交于 2019-11-27 01:52:12

问题


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?


回答1:


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



回答2:


I think this will work, although I'm not sure:

template<class T, class M>
struct mforward {
  using type = M&&; 
};
template<class T, class M>
struct mforward<T&, M> {
  using type = M&; 
};

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


来源:https://stackoverflow.com/questions/8570655/perfect-forwarding-a-member-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!