template <typename Key, typename Resource>
class ResourceHolder {
std::unordered_map<Key, std::unique_ptr<Resource>> resources;
public:
Resource& get(const Key& key) const {
if (auto resource = resources.find(key); resource != std::end(resources)) {
return *(resource->second);
}
}
inline const Resource& operator[](Key&& key) const {
return get(std::forward<Key>(key));
}
};
我正在尝试学习移动语义,并且想知道我在
std::forward
中使用operator[]
的方法-正确吗?
最佳答案
不,此用法不正确。您想要的是将key
值作为转发引用,如下所示:
template <typename T>
const Resource& operator[](T&& key) const;
然后,您可以完美转发
key
。这可能令人困惑,但是让我们看一下为什么这样做是必要的。说Key = int
。实例化模板时,operator[]
是什么样的?const Resource& operator[](int&& key) const;
请注意,此处我们采用的是r值引用,而不是转发引用。您需要的是一个转发引用,由于模板的减少和引用的折叠,实例化该引用后,其值将评估为正确的类型。
但是,在您的示例中,完美转发的值(value)丢失了,因为您只有一个使用const引用的
get
函数。在这种用例中,除了const引用operator[]
外,我什么都没有用。
关于c++ - 运算符中的完美转发[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62001045/