gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:57:43 26 4
gpt4 key购买 nike

我想要实现的是这样的:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com