【发布时间】: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&& input) 和onProcess(const Input& input) 总是做同样的事情。我怎样才能同时为 const 左值引用 和 rvalue 引用 设置一个重载,拥有一个 const 左值引用 会消耗我的内存和性能吗?另外,如果我的onProcess(Input& 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