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;
}
Run Code Online (Sandbox Code Playgroud)
Now if I provide an overload to that whatever method that takes a reference as well.
template<typename T>
static void whatever(T& container);
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)