从可变模板创建 std::list unique_ptr
Create std::list unique_ptr from variadic template
我尝试从 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)...));
}
语法为:
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
}
我尝试从 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)...));
}
语法为:
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
}