c++ - 将可能的左值引用模板转换为左值

标签 c++ templates c++11

我想要实现的是这样的:

template<typename T>
void foo(T t) {
    TWithoutReferenceType t1 = Magic(t); //some magic here
}

TWithoutReferenceT 是同一类型但没有引用,例如:

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/

相关文章:

c++ - 默认模板参数的范围是什么?

c# - Resharper 和自定义实时模板不工作

c++ - 理解右值引用

c++ - 延迟crtp基类中的成员函数实例化

c++ - 可变大小数组类型 ‘int [size]’ 不是有效的模板参数

c++ - 条件 cin 给出堆叠的 cout 消息

c++ - 无法编译 brian gladman aes 库

c++ - g++ 将字段的基本构造函数错误并忽略它的参数

c++ - 我应该传递一个 std::vector 还是固定数量的参数?

c++ - 在 C 中奇怪的类型转换好奇心