[英]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.