我希望弄清楚將多個成員從同一轉發參考轉發到結構的正確方法。
例子
one_field下面是將兩個欄位 (和) 從轉發參考引數轉發another_field到類建構式 ( )的示例。這就是我之前認為我們應該這樣做的方式:widgetinfo
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(std::forward<Bundle>(info).one_field, std::forward<Bundle>(info).another_field);
}
在 reddit 的 C 執行緒上有一個討論,列出了 9 種轉發結構成員欄位的方法。這證實了使用這個習慣用法來轉發單個成員欄位是可以的,但這對于forward.
FWD(t).field: forward t.field, and invalidates t and all its members
令我擔心的是,我的示例因此是不正確的,因為 的所有欄位info都被初始std::forward<Bundle>(info). 第二個的后續欄位訪問std::forward<Bundle>(info)。所以我現在不清楚上面例子的有效性。
我們應該如何以理論上和實踐上安全的方式傳遞多個結構欄位?我非常希望不需要撰寫std::forward根據父結構型別的語意移動其引數的變體。
參考
Reddit 關于單一領域成員的討論:https ://www.reddit.com/r/cpp/comments/q4mchr/overview_of_different_ways_of_passing_struct/
對多個轉發發表評論:https ://www.reddit.com/r/cpp/comments/q4mchr/comment/hfzsidd/——發現這篇文章表明這??在“實踐中”是可以的,但考慮到 C 錯誤的微妙之處,我我很想知道這在“理論上”也是可以的!我希望因為在引擎蓋下std::forward是static_cast一個右值型別,所以其他欄位不會發生無效,如果實際呼叫移動建構式就會發生這種情況。
類似的 SO 問題(對于單個成員欄位):How to perfectly forward a struct member?
謝謝大家。
uj5u.com熱心網友回復:
轉發你已經做了正確的事情(即轉發成員作為 Bundle)并且訪問一個欄位不像使父物件無效。
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(
std::forward<Bundle>(info).one_field,
std::forward<Bundle>(info).another_field
);
}
如果你愿意,你也可以使用類似std::forward_likeC 23 的東西
template<typename Bundle>
auto make_widget(Bundle&& info) {
return widget(
std::forward_like<Bundle>(info.one_field),
std::forward_like<Bundle>(info.another_field)
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537144.html
上一篇:類模板模板外的靜態成員定義
下一篇:解決賦值建構式中的歧義C
