Cannotaccesstypealiasesofaforwardedtypewhenpassedbyreference

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.

这只是我想出的用于构建问题的示例代码。

回答

您必须从推断T类型中删除引用,例如使用std::decay_t

typename std::decay_t<T>::value_type x;


以上是Cannotaccesstypealiasesofaforwardedtypewhenpassedbyreference的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>