我在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