[英]C++ Perfect Forwarding function
I've read about perfect forwarding, but still I've got questions)我读过关于完美转发的文章,但我仍有疑问)
Consider this code考虑这段代码
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
};
My problem is that onProcess(Input&& input)
and onProcess(const Input& input)
will always do the same .我的问题是
onProcess(Input&& input)
和onProcess(const Input& input)
总是会做同样的事情。 How can I have one overload for both const lvalue reference and rvalue reference , will having one const lvalue reference cost me memory and performance?如何同时为const lvalue reference和rvalue reference设置一个重载,拥有一个const lvalue reference会花费我 memory 和性能吗? Also what if I had an overload with
onProcess(Input& input)
how could I solve my problem then?另外,如果我的
onProcess(Input& input)
过载怎么办,那我该如何解决我的问题呢?
UPDATE更新
My example was not using perfect forwarding, so I've corrected it for the right context of the question我的示例没有使用完美转发,因此我已针对问题的正确上下文对其进行了更正
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
};
Perfect forwarding is possible when you have a forwarding reference .当您有转发参考时,完美转发是可能的。
Example:例子:
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;
}
As for the virtual
function onProcess
, you can't have a similar construct there since virtual
functions can't be function templates.至于
virtual
function onProcess
,你不能在那里有类似的构造,因为virtual
函数不能是 function 模板。 Since both overloads are supposed to do the same thing without changing the object, only make one of those functions and take the Intput
by const&
.由于两个重载都应该在不更改 object 的情况下做同样的事情,因此只创建其中一个函数并通过
const&
获取Intput
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.