我正在包装 boost::lockfree::spsc_queue<T> queue
进入一个 RingBuffer 类,并希望能够在我的项目中使用这个 RingBuffer。但是我很难通过类构造函数将容量大小传递给队列。
环形缓冲区.hh
template<class T>
class RingBuffer {
private:
int capacity;
boost::lockfree::spsc_queue<T> queue;
public:
explicit RingBuffer(int size)
{
if(size < 2){
capacity = 2;
} else {
capacity = size;
}
queue(capacity); // Error here. Not working in this way
}
~RingBuffer()
= default;
int Insert(); // queue.push()
int Extract(); // queue.pop()
}
在 main.cpp 中
int main(int argc, char *argv[]) {
auto ringBuffer = new RingBuffer<int>(3); // capacity size: 3
// ...
// other things done
// ...
delete ringBuffer;
return 0;
}
我希望这对我有用,但我收到错误:
error: type 'boost::lockfree::spsc_queue<int>' does not provide a call operator
. @ queue(capacity)
在 RingBuffer 的构造函数中。
那么,我该如何实现呢?
最佳答案
spsc_queue
的接口(interface)中没有 operator()(int)
。现在您的编译器向 queue(capacity);
提示 - 这会在 queue
实例上调用 opearator()(int)
。
我假设您的意图是调用 spsc_queue
的 ctor 并将 capacity 作为参数。
因此添加辅助方法来计算此容量并将其传递给初始化列表上的队列构造函数:
template<class T>
class RingBuffer {
private:
int capacity;
boost::lockfree::spsc_queue<T> queue;
public:
int getCapacity(int size) {
if(size < 2){
capacity = 2;
} else {
capacity = size;
}
return capacity;
}
explicit RingBuffer(int size)
: queue( getCapacity(size) ) // call ctor on initialization list
{
}
~RingBuffer()
= default;
int Insert(); // queue.push()
int Extract(); // queue.pop()
};
关于c++ - 如何通过构造函数将容量大小传递给无锁 spsc_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268969/