我在VS 2015 Community Edition中运行以下所有代码。通用引用:无法将参数从'int'转换为'int &&'
当我尝试执行在Code Review中向我建议的建议时,我在代码中出现错误。我遇到问题的部分是将参数TryPush
更改为TryPush(T&& val)
。
#pragma once
#include <atomic>
#include <memory>
template <typename T> class RingBuffer {
public:
/*
Other functions
*/
void Push(T val) {
while (!TryPush(val));
}
private:
/*
Other functions
*/
//Private Member Functions
bool TryPush(T && val) {
const std::size_t current_write = write_position.load(std::memory_order_acquire);
const std::size_t current_read = read_position.load(std::memory_order_acquire);
const std::size_t next_write = increment_index(current_write);
if (next_write == current_read) { return false; }
_ring_buffer_array[current_write] = std::move(val);
write_position.store(next_write, std::memory_order_release);
return true;
}
std::size_t increment_index(std::size_t index) {
return (index + 1) % _buffer_capacity;
}
//Private Member Variables
std::atomic<std::size_t> read_position = 0;
std::atomic<std::size_t> write_position = 0;
std::size_t _buffer_capacity;
std::unique_ptr<T[], RingBufferFree> _ring_buffer_array;
};
每当我试图编译此代码我碰到下面的错误布尔RingBuffer :: TryPush(T & &):不能转换从参数1 '诠释' 到'廉政& &。令我困惑的是,如果将代码更改为
#pragma once
#include <atomic>
#include <memory>
template <typename T> class RingBuffer {
public:
/*
Other functions
*/
void Push(T && val) {
while (!TryPush(val));
}
private:
/*
Other functions
*/
//Private Member Functions
bool TryPush(T val) {
const std::size_t current_write = write_position.load(std::memory_order_acquire);
const std::size_t current_read = read_position.load(std::memory_order_acquire);
const std::size_t next_write = increment_index(current_write);
if (next_write == current_read) { return false; }
_ring_buffer_array[current_write] = std::move(val);
write_position.store(next_write, std::memory_order_release);
return true;
}
std::size_t increment_index(std::size_t index) {
return (index + 1) % _buffer_capacity;
}
//Private Member Variables
std::atomic<std::size_t> read_position = 0;
std::atomic<std::size_t> write_position = 0;
std::size_t _buffer_capacity;
std::unique_ptr<T[], RingBufferFree> _ring_buffer_array;
};
它编译并运行。我在斯科特迈尔的blog post的印象下,TryPush(T && val)
是一个通用的引用,我应该能够使用它,如第一个代码片段所示,然后将值移入数组,从而确保代码工作,无论是左值还是右值被传递给函数。它似乎工作,如果它的公众面临Push
方法,因此我有点困惑,究竟是怎么回事。我一定在这里错过了一些东西,并想知道是否有人能澄清究竟是什么。谢谢。
编辑 调用像这样
RingBuffer<int> r(50);
for (int i = 0; i < 20; i++) {
r.Push(i + 1);
}
你怎么称呼'TryPush'? – NathanOliver