如何解决为什么不能在 C++ 中创建一个包含一个元组和一个 unique_ptr 作为值的元组?
将 std::unique_ptr
放在 std::tuple
中没有任何问题,但是当 tuple
包含另一个 tuple
和 unique_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,std::unique_ptr<Entity>>´
note: candidate constructor template not viable: cannot convert initializer list argument to ´std::allocator_arg_t´
这里的问题究竟是什么?
解决方法
TL;DR
更改您的代码以使其读取
std::tuple<std::tuple<int,int>,std::unique_ptr<Derived>> tupleB{std::make_tuple(1,1),std::move(new Derived)};
详情
你的编译器会告诉你哪里出了问题。它说(在这种情况下是 MSVC)
错误 C2440:“初始化”:无法从“初始化列表”转换为“std::tuplestd::tuple
所以不要像这样使用初始化列表
std::tuple<std::tuple<int,std::move(new Derived)};
问题如下:
当一个容器用大括号内的值初始化时,比如 {1,1},这被推导出为类型 std::initializer_lists<const char *>
。反过来,编译器会寻找一个容器构造函数,它接受一个初始化列表作为参数。
std::forward_as_tuple(1,1)
而不是 {1,1}
应该可以工作。
你不能使用初始化列表来初始化一个元组,你必须像下面这样使用std::make_tuple
:
std::tuple<std::tuple<int,std::unique_ptr<Entity>> tupleB {std::make_tuple<int,int>(1,std::move(new Entity)};
,
使用 {1,1}
代替 std::make_tuple(1,1)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。