【问题标题】:C++ Perfect Forwarding functionC++完美转发功能
【发布时间】:2022-01-22 20:47:48
【问题描述】:

我读过关于完美转发的文章,但我仍有疑问)

考虑这段代码


template<typename Input , typename Output>
struct Processor 
{
    Output process(Input&& input)
    {
        startTimer(); // Starting timer
        auto data = onProcess(std::forward<Input>(input)); // Some heavy work here
        stopTimer(); // Stopping timer
        logTimer(); // Logging how many ms have passed
        return data;
    }

protected:
    Output onProcess(Input&& input) = 0; // one overload for rvalue-references
    Output onProcess(const Input& input) = 0; // one overload for const lvalue-references
};

我的问题是onProcess(Input&amp;&amp; input)onProcess(const Input&amp; input) 总是做同样的事情。我怎样才能同时为 const 左值引用rvalue 引用 设置一个重载,拥有一个 const 左值引用 会消耗我的内存和性能吗?另外,如果我的onProcess(Input&amp; input) 过载了怎么办?那么我该如何解决我的问题呢?

更新

我的示例没有使用完美转发,因此我已针对问题的正确上下文对其进行了更正

template<typename Input , typename Output>
struct Processor 
{

    template<class I, 
    std::enable_if_t<std::is_same_v<std::decay_t<I>, Input>, int>=0>
    Output process(I&& input)
    {
        startTimer(); // Starting timer
        auto data = onProcess(std::forward<I>(input));
        stopTimer(); // Stopping timer
        logTimer(); // Logging how many ms have passed
        return data;
    }
protected:
    Output onProcess(Input&& input) = 0; // one overload for rvalue-references
    Output onProcess(const Input& input) = 0; // one overload for const lvalue-references
};

【问题讨论】:

  • 这不是完美的转发。阅读通用参考文献
  • 谢谢更新问题
  • 对不起,我不想指出你应该改进你的问题。我只是指出了一个错误的前提。收到答案后最好不要大量编辑问题

标签: c++ reference rvalue-reference lvalue perfect-forwarding


【解决方案1】:

如果您有forwarding reference,则可以完美转发。

例子:

template<class I, std::enable_if_t<std::is_convertible_v<I, Input>, int> = 0>
Output process(I&& input)
{
    startTimer(); // Starting timer
    auto data = onProcess(std::forward<I>(input));
    stopTimer(); // Stopping timer
    logTimer(); // Logging how many ms have passed
    return data;
}

至于virtual 函数onProcess,因为virtual 函数不能是函数模板,所以你不能在那里有类似的构造。由于两个重载都应该在不更改对象的情况下做同样的事情,因此只创建其中一个函数并通过const&amp; 获取Intput

【讨论】:

  • std::is_same_v&lt;I,Input&gt; 限制太多,您可能需要std::is_same_v&lt;std::decay_t&lt;I&gt;, Input&gt;。或std::is_convertible.
  • 谢谢会更新我的问题))
  • @HrantNurijanyan 更新了我的答案
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
相关资源
最近更新 更多