【问题标题】:Perfect forwarding in operator[]operator[] 中的完美转发
【发布时间】:2020-09-12 00:15:37
【问题描述】:
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));
    }
};

我正在尝试学习移动语义,我想知道我在 operator[] 中对 std::forward 的使用 - 是否正确?

【问题讨论】:

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


    【解决方案1】:

    不,这种用法不正确。您想要的是将您的 key 值作为转发参考,如下所示:

    template <typename T>
    const Resource& operator[](T&& key) const;
    

    那么,你就可以完美转发key了。这可能令人困惑,但让我们看看为什么这是必要的。说Key = int。当我们实例化模板时,operator[] 是什么样的?

    const Resource& operator[](int&& key) const;
    

    请注意,我们在这里采用的是 r 值引用,而不是转发引用。你想要的是一个转发引用,由于模板推导和引用折叠,它在实例化时会评估为正确的类型。

    但是,在您的示例中,完美转发的价值丢失了,因为您只有一个 get 函数,该函数采用 const 引用。在这个用例中,我认为除了 const 引用 operator[] 之外没有任何用处。

    【讨论】:

    • 所以这对于模板化函数来说很好,但我怀疑你实际上并不希望将它与Key 的类值分开模板化。
    • 没有功能模板就无法完美转发。
    猜你喜欢
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多