c++ - 运算符中的完美转发[]

标签 c++ c++11 move-semantics perfect-forwarding

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/

相关文章:

c++ - 什么是 MaxDetect 1-wire 总线?

C++11 move(x) 实际上意味着 static_cast<X&&>(x)?

c++ - 可变参数构造函数优先于用户提供的 move 构造函数,默认情况下除外

c++ - 为什么对象可能是 "moved"甚至缺少 move 构造函数和 move 赋值运算符?

c++ - 通用输出类签名的正确类型

c++ - 根据条件将元素从一个 forward_list 转移到另一个

c++ - std::thread 的线程安全数组?

c++ - 如何在 C++ 中实现多维映射的常量正确性

c++ - 接受字符串输入

c++ - 将 unsigned char* 强制转换为 char* 并将取消引用的指针视为它真的指向 char 是否安全?