【问题标题】:Why isn't it possible to make a tuple which contains a tuple and a unique_ptr as values in C++?为什么不能在 C++ 中创建一个包含元组和 unique_ptr 作为值的元组?
【发布时间】:2021-05-02 09:18:31
【问题描述】:

std::unique_ptr 放在std::tuple 中没有任何问题,但是当tuple 包含另一个tupleunique_ptr 作为元素时,编译器会抛出错误。

示例:

    std::tuple<int, std::unique_ptr<Entity>> tupleA {1, std::move(new Entity)};

    //this line throws an error!
    std::tuple<std::tuple<int, int>, std::unique_ptr<Entity>> tupleB {{1, 1}, std::move(new Entity)};

第二行,创建 `tupleB` 抛出以下错误:
        error: no matching constructor for initialization of ´std::tuple<std::tuple<int, int>,std::unique_ptr<Entity>>´
        note: candidate constructor template not viable: cannot convert initializer list argument to ´std::allocator_arg_t´

这到底是什么问题?

【问题讨论】:

  • 在构造函数中尝试std::tuple&lt;int, int&gt;{1, 1}
  • 应该是:auto tupleB = std::make_tuple(std::make_tuple(1, 1), std::make_unique&lt;Entity&gt;());

标签: c++ pointers stl unique-ptr stdtuple


【解决方案1】:

TL;DR

更改您的代码,使其读取

std::tuple<std::tuple<int, int>, std::unique_ptr<Derived>> tupleB{std::make_tuple(1,1), std::move(new Derived)};

详情

您的编译器会告诉您哪里出了问题。它说(在这种情况下为 MSVC)

错误 C2440: 'initializing': 无法从 'initializer list' 转换为 'std::tuplestd::tuple>'

所以不要像这样使用初始化列表

std::tuple<std::tuple<int, int>, std::unique_ptr<Derived>> tupleB{std::make_tuple(1,1), std::move(new Derived)};

问题如下:

当使用大括号内的值初始化容器时,例如 { 1, 1},这会被推断为类型 std::initializer_lists&lt;const char *&gt;。反过来,编译器会寻找一个容器构造函数,该构造函数将初始化列表作为参数。

【讨论】:

    【解决方案2】:

    std::forward_as_tuple(1, 1) 而不是 {1, 1} 应该可以工作。

    【讨论】:

      【解决方案3】:

      你不能使用初始化列表来初始化一个元组,你必须使用std::make_tuple,如下所示:

      std::tuple<std::tuple<int, int>, std::unique_ptr<Entity>> tupleB {std::make_tuple<int, int>(1, 1), std::move(new Entity)};
      

      【讨论】:

        【解决方案4】:

        std::make_tuple(1, 1)代替{1, 1}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-30
          • 1970-01-01
          相关资源
          最近更新 更多