用于将unique_ptr的向量初始化为基本类型的可变参数构造 [英] Variadic construction for initialising vector of unique_ptr to base type

查看:59
本文介绍了用于将unique_ptr的向量初始化为基本类型的可变参数构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个示例程序,其中容器类需要通过基类指针存储项目列表。从C ++ 11/14开始,自然的选择是在我遇到的情况下使用std :: unique_ptr和可变参数模板。

Below is an example program where a 'Container' class needs to store a list of 'Items' via a base class pointer. Having started with C++11/14 the natural choice would be to use std::unique_ptr and variadic templates in the case I have.

但是,作为新手,我无法理解如何以编译的方式将可变参数列表转换为unique_ptr向量的初始化列表。非常感谢您的帮助,因为到目前为止,我在网上找不到任何可以帮助我解决此问题的内容(尽管可能在那里!)。

However being new I cannot fathom how to convert the variadic list into and initialiser list for the vector of unique_ptr in a manner that compiles. Help is greatly appreciated as I have failed to find anything online that helps me with this issue so far (albeit likely out there!).

预先感谢:

// Example program
#include <iostream>
#include <string>
#include <memory>
#include <vector>

struct Item
{
};


struct Container
{
    template<typename... Items>
    Container( Items&&... items ) 
    : items_( {std::make_unique<Items>(items)...} ) //<<TODO: How, VC compiler times out with this code!?
    {
    }

    std::vector<std::unique_ptr<Item>> items_;
};

struct A : Item { A(float){}  };
struct B : Item {  };
struct C : B    { C(float){} };
struct D : Item { D(float){} };

int main()
{
  Container x( A(1), C(2), D(3) );

  return 0;
}


推荐答案

问题是您不能将 unique_ptr intializer_list 中移出。阅读此问题以获取更多详细信息。

The issue is that you cannot move unique_ptr out from intializer_list. Read this question for more details.

此解决方案使用此答案中的技术,而不是使用 intializer_list ,可以使用普通数组构造项目。

This solution use the technique in this answer that instead of using intializer_list, you can use plain array to construct items.

struct Container
{
    template<typename... Items>
    Container( Items&&... items ) 
    : items_()
    {
        std::unique_ptr<Item> itemArr[] = {std::make_unique<Items>(std::move(items))...};
        items_ = std::vector<std::unique_ptr<Item>> {std::make_move_iterator(std::begin(itemArr)), std::make_move_iterator(std::end(itemArr))};
    }

    std::vector<std::unique_ptr<Item>> items_;
};

在线演示

这篇关于用于将unique_ptr的向量初始化为基本类型的可变参数构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆