问题描述
有关如何插入而不复制地图值.
See this answer for how to insert into stdmap without making copies of the map value.
从该答案继续-假设我的 Foo
类型看起来像这样:
Continueing from that answer - suppose my Foo
type looks something like this:
struct Foo {
const int& intref_;
std::mutex mutex_;
}
然后使用像这样的聚合初始化来初始化
Then initialized using aggregate-initialization like this
Foo{7}
或
Foo{7, std::mutex()}
以某种方式可以将其放置到地图中吗?:
Would it be somehow possible to be emplaced into the map with type ?:
std::map<size_t, Foo> mymap;
我知道我可以为 Foo
写一个构造函数-但是可以用聚合初始化来代替吗?
I know I could just write a constructor for Foo
- but can it be done with aggregate initialization instead ?
链接到编译器资源管理器:
相关的c ++参考:
https://en.cppreference.com/w/cpp/container/map/try_emplace
https://en.cppreference.com/w/cpp/language/aggregate_initialization
推荐答案
您可以利用类型转换来间接构建您的建筑
You may exploit casts to indirect your construction
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)...};
}};
}
并将其用作
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)));
}
请注意,您不能通过将临时目录绑定到非堆栈引用来延长其使用寿命.
Note you can't prolong a temporary's lifetime by binding it to a non-stack reference.
这篇关于使用聚合初始化时,是否可以在地图中进行无复制放置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!