在 std::map 中插入模板 class 并在插入时构造

Insert templated class in std::map with construction at insertion

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

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_construct and std::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::pair 用于 key/value 存储。 std::pair::pair has an overload that takes an 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.