假設我們有一個類模板Foo,它有一個型別模板引數,它可以從其建構式中的引數推匯出來。如果我們使用std::make_unique來構造 的實體Foo,有沒有辦法讓Foo的建構式推匯出模板引數,就像它的建構式被正常呼叫一樣?這是實作這一目標的最簡單方法嗎?
std::make_unique< decltype(Foo{...}) > (...);
這看起來很干凈,但是如果Foo的建構式需要很多引數,它可能會變成一個非常丑陋的行。
uj5u.com熱心網友回復:
您可以利用輔助函式將丑陋的代碼包裝成漂亮的包裝器。那看起來像
template <typename... Args>
auto make_foo_ptr(Args&&... args)
{
return std::make_unique<decltype(Foo{std::forward<Args>(args)...})>(std::forward<Args>(args)...);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380301.html
