gpt4 book ai didi

c++ 带参数的新类数组

转载 作者:行者123 更新时间:2023-11-28 05:41:14 24 4
gpt4 key购买 nike

引用https://github.com/cameron314/readerwriterqueue ,有一个示例代码如下:

ReaderWriterQueue<int> q(100);       // Reserve space for at least 100 elements up front

q.enqueue(17); // Will allocate memory if the queue is full
bool succeeded = q.try_enqueue(18); // Will only succeed if the queue has an empty slot (never allocates)
assert(succeeded);

int number;
succeeded = q.try_dequeue(number); // Returns false if the queue was empty

assert(succeeded && number == 17);

// You can also peek at the front item of the queue (consumer only)
int* front = q.peek();
assert(*front == 18);
succeeded = q.try_dequeue(number);
assert(succeeded && number == 18);
front = q.peek();
assert(front == nullptr); // Returns nullptr if the queue was empty

假设我想为 ReaderWriterQueue 构造一个参数为 100 的数组,我该如何定义 var ?!

ReaderWriterQueue<int> qp[1024] ;  

没关系,但我喜欢参数为 100 的所有 1024 个,

ReaderWriterQueue<int>(100) qp[1024] ;

不会编译,我尝试使用指针:

ReaderWriterQueue<int>* qptr;
qptr = new ReaderWriterQueue<int>(1024) ;

会工作,但没有参数 100,

qptr = new ReaderWriterQueue<int>(100) (1024) ;

不会编译,那么我如何制作一个 1024 的 ReaderWriterQueue 数组,所有这些都是用参数 100 构造的?!

最佳答案

由于 ReaderWriterQueue 既不可复制也不可移动,您可以使用 http://en.cppreference.com/w/cpp/types/aligned_storage 中的 static_vector

template<class T, std::size_t N>
class static_vector
{
// properly aligned uninitialized storage for N T's
typename std::aligned_storage<sizeof(T), alignof(T)>::type data[N];
std::size_t m_size = 0;

public:
// Create an object in aligned storage
template<typename ...Args> void emplace_back(Args&&... args)
{
if( m_size >= N ) // possible error handling
throw std::bad_alloc{};
new (data + m_size) T(std::forward<Args>(args)...);
++m_size;
}

// Access an object in aligned storage
const T& operator[](std::size_t pos) const
{
return *reinterpret_cast<const T*>(data + pos);
}

// Delete objects from aligned storage
~static_vector()
{
for (std::size_t pos = 0; pos < m_size; ++pos) {
reinterpret_cast<const T*>(data+pos)->~T();
}
}
};

然后使用它

static_vector<ReaderWriterQueue<int>, 1024> queues;

for (int i = 0; i != 1024; ++i) {
queues.emplace_back(100)
}

关于c++ 带参数的新类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37062430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com