Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

c++ - errors with std::vector<std::reference_wrapper<move_t>>

The following data types have been defined:

struct move_t {
    int     pos;
    int     value;
};

using moves_t = std::vector<move_t>;

There are two arrays

moves_t data1, data2;

I am trying to form a vector of references to elements from the specified arrays

std::vector<std::reference_wrapper<move_t>> moves;

moves.insert(std::end(chainMoves), std::begin(data1), std::end(data1));
moves.insert(std::end(chainMoves), std::begin(data2), std::end(data2));

But I get the following error

Error C2665 'std::reference_wrapper<move_t>::reference_wrapper': none of the 2 overloads could convert all the argument types

Please tell me what the error is and how to fix it

minimal code:

#include <conio.h>

#include <functional>
#include <vector>

struct move_t {
    int                 pos;
    int                 variant;

    move_t(const int l_pos = -1, const int l_variant = 0)
        : pos(l_pos), variant(l_variant)
    {}
};

using moves_t = std::vector<move_t>;

struct moves_fork_t {
    moves_t             moves;

    moves_fork_t() {
        moves.reserve(100);
    }
};

struct moves_chain_t {
    moves_fork_t        forks[2];
};

using moves_chains_t = std::vector<moves_chain_t>;

int main() {

    moves_chains_t chains;

    std::vector<std::reference_wrapper<move_t>> moves;
    moves.reserve(100);

    for (const auto& chain : chains)
    {
        moves.insert(std::end(moves), std::begin(chain.forks[0].moves), std::end(chain.forks[0].moves));
        moves.insert(std::end(moves), std::begin(chain.forks[1].moves), std::end(chain.forks[1].moves));
    }

    _getch();
}

P.S.

The main task was to combine two arrays into one, but without unnecessary copying, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your program attempts to initialize std::reference_wrapper<T> with an lvalue of type const T. This can't work for obvious reasons - the same reasons that const int x=42; int& r = x; doesn't work.

Either drop const in for (const auto& chain : chains), or make it std::vector<std::reference_wrapper<const move_t>> moves;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...