gpt4 book ai didi

c++ - 在插入时构造的 std::map 中插入模板化类

转载 作者:搜寻专家 更新时间:2023-10-31 02:09:55 25 4
gpt4 key购买 nike

我正在尝试将没有复制构造函数的模板化类的实例插入到映射中。下面的代码不起作用,因为编译器想要在 emplace 函数中调用复制构造函数。我不明白为什么,因为我从C++ reference明白了该位置不会移动或复制:

Careful use of emplace allows the new element to be constructed while avoiding unnecessary copy or move operations.

这是我的代码:

#include <map>
#include <string>

template<typename T> class Class_a
{
public:
Class_a(T t1, T t2) : t1_(t1), t2_(t2) {}
~Class_a() {}
Class_a(const Class_a&) = delete;
Class_a& operator=(const Class_a&) = delete;
Class_a(Class_a&&) = delete;
private:
const T t1_;
const T t2_;
};

template<typename T>
using Class_a_map = std::map<std::string, Class_a<T>>;

int main()
{
Class_a_map<double> class_a_map;
std::string name = "test";
double number1 = 42;
double number2 = 43;
class_a_map.emplace(name, Class_a<double>(number1, number2));

return 0;
}

最佳答案

您可以使用 std::piecewise_constructstd::forward_as_tuple就地创建您的对象。

class_a_map.emplace(
std::piecewise_construct,
std::forward_as_tuple(name),
std::forward_as_tuple(number1, number2)
);

live wandbox example


std::map::emplace 完美地将一堆参数转发给用于键/值存储的底层 std::pairstd::pair::pair有一个需要 std::piecewise_construct_t 的重载作为它的第一个参数,然后是两个 std::tuple 实例:第一个将用于构造 .first ,第二个将用于构造 .second 就位。

来自 cppreference,关于 std::pair 的分段构造函数:

Forwards the elements of first_args to the constructor of first and forwards the elements of second_args to the constructor of second. This is the only non-default constructor that can be used to create a pair of non-copyable non-movable types.

关于c++ - 在插入时构造的 std::map 中插入模板化类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com