【问题标题】:Create std::list unique_ptr from variadic template从可变参数模板创建 std::list unique_ptr
【发布时间】:2021-12-19 18:59:26
【问题描述】:

我尝试从 args 创建 std::list,但是当传递超过 0 个参数时,会出现错误“没有匹配的函数用于调用 'make_unique'”。我认为错误是我一次将所有参数传递给 make_unque,但我不明白如何打开捆绑包 2 次。

template<class ...Args>
void do(Args&&... args)
{
    std::list<std::unique_ptr<Base>> obj(std::make_unique<Child>(std::forward<Args>(args)...));
}

【问题讨论】:

  • 很确定你需要obj{std::make_unique&lt;Child&gt;(std::forward&lt;Args&gt;(args))...}
  • @NathanOliver:但问题在于 initializer_list 具有 const 元素,并且无法移动。
  • @Jarod42 哦,是的,那些讨厌的 const 元素。好吧,这使这变得更加复杂。
  • 看起来这里有黑客攻击:stackoverflow.com/questions/46737054/…

标签: c++ c++14 variadic-templates


【解决方案1】:

语法是:

template<class ...Args>
void do(Args&&... args)
{
    std::list<std::unique_ptr<Base>> obj{std::make_unique<Child>(std::forward<Args>(args))...};
}

但您不能从std::initializer_list 移动元素(它们的元素是const)。

一个可能的解决方法是emplace:

template<class ...Args>
void do(Args&&... args)
{
    std::list<std::unique_ptr<Base>> obj;

#if 0 // C++17
    (obj.emplace(std::make_unique<Child>(std::forward<Args>(args)), ...);
#else // C++11 and C++14
    int dummy[] = {0, (obj.emplace(std::make_unique<Child>(std::forward<Args>(args)), 0)...};
    static_cast<void>(dummy); // avoid warning for unused variable.
#endif
}

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多