C++ 运营商中的完美转发[] 模板 班级资源持有者{ std::无序的地图资源; 公众: 资源和获取(常量键和键)常量{ if(auto resource=resources.find(key);resource!=std::end(resources)){ 返回*(资源->秒); } } 内联常量资源和运算符[](键和键)常量{ 返回get(std::forward(key)); } };
我正在尝试学习移动语义,我想知道我在C++ 运营商中的完美转发[] 模板 班级资源持有者{ std::无序的地图资源; 公众: 资源和获取(常量键和键)常量{ if(auto resource=resources.find(key);resource!=std::end(resources)){ 返回*(资源->秒); } } 内联常量资源和运算符[](键和键)常量{ 返回get(std::forward(key)); } };,c++,c++11,move-semantics,perfect-forwarding,C++,C++11,Move Semantics,Perfect Forwarding,我正在尝试学习移动语义,我想知道我在操作符[]中使用的std::forward-正确吗?不,这个用法不正确。您想要的是将键值作为转发引用,如下所示: template <typename Key, typename Resource> class ResourceHolder { std::unordered_map<Key, std::unique_ptr<Resource>> resources; public: Resource&
操作符[]
中使用的std::forward
-正确吗?不,这个用法不正确。您想要的是将键
值作为转发引用,如下所示:
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));
}
};
请注意,我们在这里使用的是r值引用,而不是转发引用。您需要的是一个转发引用,由于模板推导和引用折叠,在实例化时会计算为正确的类型
但是,在您的示例中,完美转发的值丢失了,因为您只有一个
get
函数,该函数采用常量引用。在这个用例中,我认为除了常量引用操作符[]
之外,其他任何东西都是有用的。因此这对于模板化函数来说是很好的,但我怀疑您实际上不希望将其模板化为与键的类值分开的。没有函数模板,就无法实现完美的转发。
template <typename T>
const Resource& operator[](T&& key) const;
const Resource& operator[](int&& key) const;