Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to forward a non-movable object in std::pair

I can’t figure out the syntax to perfectly forward a pair when it contains something that’s non-movable

#include <mutex>
#include <list>
#include <utility>

struct A
{
    A(int x)
    {

    }
};

int main()
{
    std::list<std::pair<std::mutex, std::mutex>> v;
    v.emplace_back(); // ok

    std::list<std::pair<A, A>> v2;
    v2.emplace_back(3, 4); // ok

    std::list<std::pair<A, std::mutex>> v3;
    v3.emplace_back(3, std::forward<std::mutex>(std::mutex{})); // help
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You must construct the std::mutex in-place from an empty argument list. This can be done using the std::piecewise_construct constructor, which allows you to forward arguments for the constructors of the two elements as std::tuples.

// for std::forward_as_tuple
#include<tuple>

// ...

v3.emplace_back(std::piecewise_construct, std::forward_as_tuple(3), std::forward_as_tuple());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading