[英]C++ use std::fill for class with deleted assign operator
Suppose I have a range of objects假设我有一系列对象
class X {
public:
X()
: X(0) {
}
X(size_t num)
: x_(num) {
}
X(const X& other) = delete;
X& operator=(const X& other) = delete;
X(X&& other) {
x_ = exchange(other.x_, 0);
}
X& operator=(X&& other) {
x_ = exchange(other.x_, 0);
return *this;
}
size_t GetX() const {
return x_;
}
private:
size_t x_;
};
With this in mind I can't use std::fill as operator= is deleted.考虑到这一点,我不能使用 std::fill 因为 operator= 被删除。 What is the right way to fill the range for this kind of object?
填充这种 object 范围的正确方法是什么?
Source object of std::fill
is const
. std::fill
的源 object 是const
。 const object cannot be used as source of move operation. const object 不能用作移动操作的源。
You can add helper class with conversion operator to X
, every time when *first = value;
您可以将带有转换运算符的助手 class 添加到
X
,每次*first = value;
(look at possible implementation of std::fill ) is called, temporary of X is returned and move operation is performed: (查看std::fill 的可能实现)被调用,返回 X 的临时值并执行移动操作:
template<size_t N>
struct Helper {
X MakeTemp() const { return X(N); }
operator X () const { return MakeTemp(); }
};
int main(){
std::vector<X> v;
v.resize(10);
std::fill(v.begin(), v.end(),Helper<10>{});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.