Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access type aliases of a forwarded type when passed by reference

Tags:

c++

templates

My question revolves around the code below:

template<typename T>
static void whatever(T&& container) {
  typename T::value_type x;
  std::cout << x << std::endl;
}

struct something {
  using value_type = int;

  const char* name;
};

int main() {
  whatever(something{});  // passes by rvalue, perfectly fine.
  something x;
  whatever(x);  // deduces the type as something& and complains ::value_type doesn't exist.
  return 0;
}

Now if I provide an overload to that whatever method that takes a reference as well.

template<typename T>
static void whatever(T& container);

The problem would go away but I have the exact same code for both methods and I'm wondering if there is a nice way to put this all into one method.

This is just an example code I came up with to frame the question.

like image 573
Peyman Avatar asked Nov 25 '25 15:11

Peyman


1 Answers

You have to drop reference from deduced T type, for example by using std::decay_t:

typename std::decay_t<T>::value_type x;
like image 142
rafix07 Avatar answered Nov 27 '25 05:11

rafix07



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!