问题描述
我制作了一个自定义实用程序函数,用于从给定范围和起始索引中创建一个子范围。
这非常方便,但是无法在带有std::unique_ptr
的容器上使用。
我的代码:
#include <algorithm>
#include <ranges>
#include <iostream>
#include <memory>
#include <vector>
template <std::ranges::random_access_range R>
auto range_from(R r,int t) {
return std::ranges::subrange(std::begin(r) + t,std::end(r));
}
int main() {
std::vector<int> v {1,2,3,4};
std::vector<std::unique_ptr<int>> u;
u.emplace_back(std::make_unique<int>(1));
u.emplace_back(std::make_unique<int>(2));
u.emplace_back(std::make_unique<int>(3));
u.emplace_back(std::make_unique<int>(4));
std::vector<int> v2 (4);
std::vector<std::unique_ptr<int>> u2 (4);
std::ranges::copy(v | std::ranges::views::drop(2),v2.begin()); // OK
std::ranges::copy(range_from(v,2),v2.begin()); // OK
std::ranges::move(u | std::ranges::views::drop(2),u2.begin()); // OK
// std::ranges::move(range_from(u,u2.begin()); // FAIL
}
为什么行
std::ranges::move(range_from(u,u2.begin()); // FAIL
无法编译?我该如何解决? std::ranges::views::drop
太冗长了。
编译器输出给出:
In file included from /opt/wandBox/gcc-head/include/c++/11.0.0/vector:66,from /opt/wandBox/gcc-head/include/c++/11.0.0/functional:62,from /opt/wandBox/gcc-head/include/c++/11.0.0/pstl/glue_algorithm_defs.h:13,from /opt/wandBox/gcc-head/include/c++/11.0.0/algorithm:74,from prog.cc:1:
/opt/wandBox/gcc-head/include/c++/11.0.0/bits/stl_uninitialized.h: In instantiation of '_ForwardIterator std::uninitialized_copy(_InputIterator,_InputIterator,_ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*,std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*]':
/opt/wandBox/gcc-head/include/c++/11.0.0/bits/stl_uninitialized.h:332:37: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator,_ForwardIterator,std::allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const std::unique_ptr<int>*,std::vector<std::unique_ptr<int> > >; _ForwardIterator = std::unique_ptr<int>*; _Tp = std::unique_ptr<int>]'
/opt/wandBox/gcc-head/include/c++/11.0.0/bits/stl_vector.h:558:31: required from 'std::vector<_Tp,_Alloc>::vector(const std::vector<_Tp,_Alloc>&) [with _Tp = std::unique_ptr<int>; _Alloc = std::allocator<std::unique_ptr<int> >]'
prog.cc:25:38: required from here
/opt/wandBox/gcc-head/include/c++/11.0.0/bits/stl_uninitialized.h:137:72: error: static assertion Failed: result type must be constructible from value type of input range
137 | static_assert(is_constructible<_ValueType2,decltype(*__first)>::value,|
哦,这种解决方法也失败:
// ...
template <std::ranges::random_access_range R>
auto range_from2(R r,int t) {
return r | std::ranges::views::drop(t);
}
int main() {
// ...
std::ranges::move(range_from2(u,u2.begin()); // FAIL
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)