我有两个独立的类,每个类都维护一个有限大小的缓冲区:
class A {
private:
std::deque<uint8_t> buffer;
size_t max_size;
};
class B {
private:
static const size_t MAX_SIZE = 1024;
uint8_t buffer[MAX_SIZE];
}
现在,我还有一个不是A或B成员的函数C。此函数需要从A的开头中获取(即删除)尽可能多的字节,然后写入它到B。Ofc不允许缓冲区溢出。
问题:如何在确保A和B被封装的同时有效地做到这一点?即A,B和C不知道其他人如何实现。
出于明显的原因,我不需要想要的东西:
答案 0 :(得分:2)
class A
通过新的公共方法返回 const 迭代器。
class B
公开了一种用于复制这些字节的方法。
class A {
public:
const std::deque<uint8_t>& getBuffer() const
{
return buffer;
}
private:
std::deque<uint8_t> buffer;
size_t max_size;
size_t current_size;
};
class B {
public:
B() : max_size(MAX_SIZE), current_size(0)
{
}
void Transfer(const std::deque<uint8_t>& data)
{
size_t remaining = max_size - current_size;
size_t toCopy = data.size() > remaining ? remaining : data.size();
for (size_t i = 0; i < toCopy; i++)
{
buffer[i+current_size] = data[i];
}
current_size += toCopy;
}
private:
static const size_t MAX_SIZE = 1024;
uint8_t buffer[MAX_SIZE];
};
CopyAToB(const A& a, B& b)
{
b.Transfer(a.getBuffer());
}
答案 1 :(得分:2)
模仿标准容器。使用begin
和end
。这是我在您的用例中看到的最小界面:
class A {
private:
std::deque<uint8_t> buffer_;
size_t max_size_;
public:
using const_iterator = decltype(buffer_)::const_iterator;
auto begin() const -> const_iterator { return buffer_.begin(); }
auto end() const -> const_iterator { return buffer_.end(); }
};
class B {
private:
static const size_t MAX_SIZE = 1024;
std::array<uint8_t, MAX_SIZE> buffer_;
public:
/// fills the buffer with elements in [first, last)
/// excessive elements are ignored
/// returns the number of successfully filled elements
template <class It>
auto fill_as_much_as_possible(It first, It last) -> std::size_t
{
auto in_size = std::distance(first, last);
if (in_size > static_cast<decltype(in_size)>(MAX_SIZE))
{
last = first;
std::advance(last, MAX_SIZE);
}
auto out_last = std::copy(first, last, buffer_.begin());
return std::distance(buffer_.begin(), out_last);
}
};
auto foo(const A& a, B& b)
{
b.fill_as_much_as_possible(a.begin(), a.end());
}