Queue Errors <string &>

I have this interesting situation.

I have a group of structures that contain a string.

struct foo
{
    string mStringName;
}
vector<foo> mFoos;

I also have a line reference queue

queue<string&> mStringQueue;

And finally, I have a function that takes a string const &

void Bar(const string&);

Here is the situation.

//...in some loop
currentFoo = mFoos[index];

// Queue up the string name.
mStringQueue.push(currentFoo.mStringName);


//...Later on, go through our queue and pass each one to the function.

for (int queueIndex = 0; queueIndex < mStringQueue.size(); queueIndex++)
{
    Bar(mStringQueue.front());
    mStringQueue.pop();
}

This gives me the following compilation error:

error C2664: 'std :: queue <_Ty> :: push': cannot convert parameter 1 from 'String' to 'String & (&)'

I definitely had trouble moving the mind around line links and something else, so any help would be greatly appreciated

+3
source share
2 answers

, . , . , , , .

, .

+6

, "T ( , CopyConstructible)" "T ( , MoveConstructible)". , std:: queue < :: reference_wrapper < T β†’ .

#include <cassert>
#include <queue>
#include <functional> // std::reference_wrapper, std::ref

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;

    std::queue<std::reference_wrapper<int>> que;

    que.push(std::ref(a));
    que.push(std::ref(b));
    que.push(std::ref(c));

    while (!que.empty()) {
        que.front() += 1;
        que.pop();
    }

    assert(a == 2);
    assert(b == 3);
    assert(c == 4);
}
+1

All Articles