【发布时间】:2021-09-29 12:43:16
【问题描述】:
我有一个类,它支持克隆(通过方法clone)。我在std::unique_ptr 的向量中有一堆它的实例。
现在,我想从上述向量创建一个具有相同智能指针的std::set,理想情况下是在其构造过程中。明显的设计如下:
#include <memory>
#include <set>
#include <vector>
class A
{
public:
/// type of itself
typedef A self;
A() = default;
A(const self& another) = default;
virtual ~A() = default;
std::unique_ptr<A> clone() const
{
return std::make_unique<A>();
}
};
class SetOfA
{
public:
SetOfA() = default;
// Here is the method I would like to improve
SetOfA(const std::vector<std::unique_ptr<A> >& data)
{
//do not like this loop, prefer this to be in initialization part?
for (const auto& d : data) {
set_of_a.insert(std::move(d->clone()));
}
}
private:
std::set<std::unique_ptr <A> > set_of_a;
};
但是有没有办法在构造函数中避免 for 循环并将 std::set 构造移动到初始化部分?
【问题讨论】:
-
请注意,
std::move()在那里是多余的。clone()返回一个纯右值。 -
我相信你运气不好,除非你把“为向量编写一个单独的克隆函数”作为解决方案。
-
C++20
std::views::transform接近,但随后std::set没有构造函数来查看。 -
@aschepler 您只需要一个调用迭代器构造函数的中间函数。
template <typename Container, std::range Range> Container construct(Range&& r) { return { r.begin(), r.end() }; }