Home > Back-end >  How to forward a non-movable object in std::pair
How to forward a non-movable object in std::pair

Time:04-06

I can't figure out the syntax to perfectly forward a std::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
}

CodePudding user response:

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());
  •  Tags:  
  • c
  • Related