How to perfect forward a member variable

  • A+
Category:Languages

Consider the following code:

template<typename T> void foo(T&& some_struct) {     bar(std::forward</* what to put here? */>(some_struct.member)); } 

In the case of forwarding the whole struct I would do std::forward<T>(some_struct). But how do I get the correct type when forwarding a member?

One idea I had was using decltype(some_struct.member), but that seems to always yield the base type of that member (as defined in the struct definition).

 


Member access does the right thing here: you just need std::forward<T>(some_struct).member.

Tested with:

template <class... > struct check;  struct Foo {     int i; };  template <class T> void bar(T &&f) {     // fatal error: implicit instantiation of undefined template 'check<int &&>'     check<decltype((std::forward<T>(f).i))>{}; }  int main() {     bar(Foo{42}); } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: