'How to forward a non-movable object in std::pair
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
}
Solution 1:[1]
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());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user17732522 |
