[英]C++ Perfect Forwarding function
我读过关于完美转发的文章,但我仍有疑问)
考虑这段代码
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 lvalue reference和rvalue reference设置一个重载,拥有一个const lvalue reference会花费我 memory 和性能吗? 另外,如果我的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
};
当您有转发参考时,完美转发是可能的。
例子:
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
function onProcess
,你不能在那里有类似的构造,因为virtual
函数不能是 function 模板。 由于两个重载都应该在不更改 object 的情况下做同样的事情,因此只创建其中一个函数并通过const&
获取Intput
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.