使用聚合初始化时,是否可以在地图中进行无复制放置?

dar*_*une 1 c++ stdmap language-lawyer aggregate-initialization c++17

请参阅此答案,以了解如何在不复制地图值的情况下将其插入到

std :: map放置而不复制值

继续回答-假设我的Foo类型如下所示:

struct Foo {
  const int& intref_; 
  std::mutex mutex_;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用聚合初始化来初始化

Foo{7}
Run Code Online (Sandbox Code Playgroud)

要么

Foo{7, std::mutex()}
Run Code Online (Sandbox Code Playgroud)

是否可以通过类型将其放置到地图中?

std::map<size_t, Foo> mymap;
Run Code Online (Sandbox Code Playgroud)

我知道我可以为此写一个构造函数,Foo但是可以用聚合初始化来代替吗?

链接到编译器资源管理器:

https://godbolt.org/z/_Fm4k1

相关的c ++参考:

https://en.cppreference.com/w/cpp/container/map/try_emplace

https://en.cppreference.com/w/cpp/language/aggregate_initialization

Pas*_* By 5

您可以利用演员表来间接构建

template<typename T>
struct tag { using type = T; };

template<typename F>
struct initializer
{
    F f;
    template<typename T>
    operator T() &&
    {
        return std::forward<F>(f)(tag<T>{});
    }
};

template<typename F>
initializer(F&&) -> initializer<F>;

template<typename... Args>
auto initpack(Args&&... args)
{
    return initializer{[&](auto t) {
        using Ret = typename decltype(t)::type;
        return Ret{std::forward<Args>(args)...};
    }};
}
Run Code Online (Sandbox Code Playgroud)

并用作

struct Foo
{
  const int& intref_; 
  std::mutex mutex_;
};

void foo()
{
    int i = 42;
    std::map<int, Foo> m;
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple(0),
              std::forward_as_tuple(initpack(i)));
}
Run Code Online (Sandbox Code Playgroud)

请注意,不能通过将临时目录绑定到非堆栈引用来延长其使用寿命。