我想要实现的是这样的:
template<typename T>
void foo(T t) {
TWithoutReferenceType t1 = Magic(t); //some magic here
}
TWithoutReference
与 T
是同一类型但没有引用,例如:
Magic(int i) -> int i
Magic(int& i) -> int i
Magic(int&& i) -> int i
我不知道这对于右值引用是否可行,或者它在实践中意味着什么。
为什么我需要它:
template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(const function<ReturnType(Args...)>& func)
{
return ([=](Args... args) mutable {
static map<tuple<Args...>, ReturnType> cache;
tuple<Args...> t(args...);
auto result = cache.insert(make_pair(t, ReturnType{}));
...
例如,如果 Args ...
是 vector<double> &
我改变了元素的顺序,对应的键为 cache
也发生了变化,我不希望这种情况发生,所以我不希望将来发生关键变化作为副作用。
抱歉,如果我发布了整个代码,但我担心如果我使它更简单,我会失去问题的要点。
最佳答案
您找到的是std::remove_reference :
If the type T is a reference type, provides the member typedef type which is the type referred to by T. Otherwise type is T.
Possible implementation
template< class T > struct remove_reference {typedef T type;}; template< class T > struct remove_reference<T&> {typedef T type;}; template< class T > struct remove_reference<T&&> {typedef T type;};
您可以将 Magic
实现为
template <typename T>
typename remove_reference<T>::type Magic(T t) {
return t;
}
关于c++ - 将可能的左值引用模板转换为左值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904616/