私は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;
};
:: TryPush(T & &) ':から引数1を変換することはできません '& & int型' から' int型。私を混乱させるのは、コードを
#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)
がユニバーサルなリファレンスであり、最初のコードスニペットに示されているようにそれを使用して、値を配列に移動して、lvalueまたはrvalueが関数に渡されます。公衆がPush
の方法に直面しているとうまくいくように見えます。したがって、私は何が起こっているのか混乱しています。私はここで何かを逃しているにちがいありませんし、誰かが正確にそれが何であるかを明確にすることができるかどうか疑問に思いましたありがとう。
編集 は、あなたのコード内の普遍的な参照がありませんので、
RingBuffer<int> r(50);
for (int i = 0; i < 20; i++) {
r.Push(i + 1);
}
あなたはTryPush' 'を呼び出すにはどうすればよいですか? – NathanOliver