c++ - 如何通过构造函数将容量大小传递给无锁 spsc_queue

标签 c++ boost constructor lock-free

我正在包装 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()
};

Demo

关于c++ - 如何通过构造函数将容量大小传递给无锁 spsc_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268969/

相关文章:

c++ - 未定义行为和 C++ 语言稳定性

c++ - 多次使用 QNetworkAccessManager GET

c++ - 使用 boost 创建相对路径

c++ - 为什么我需要一个构造函数?

java - 如何让基类知道子类创建了哪些对象?

c# - 构造函数链接优先级

c++ - OpenCV - 无法使用 SurfFeatureDetector 类

c++ - 英特尔芯片组编程

c++ - 使用零长度元组 boost 异常,如何解决

c++ - 使用 boost 属性树读取 int 数组