我已閱讀有關完美轉發的內容,但仍有疑問)
考慮這個代碼
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 參考會消耗我的記憶體和性能嗎?另外,如果我過載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
};
uj5u.com熱心網友回復:
當您有轉發參考時,完美轉發是可能的。
例子:
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;
}
至于virtualfunction onProcess,你不能在那里有類似的構造,因為virtual函式不能是函式模板。由于兩個多載都應該在不更改物件的情況下執行相同的操作,因此只需創建其中一個函式并采用Intputby const&。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388766.html
