vendredi 1 septembre 2017

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

I am trying to insert an instance of a templated class that does not have a copy constructor into a map. The code below does not work, because at the emplace function the compiler wants to call the copy constructor. I do not understand why, because I understood from the C++ reference that emplace does not move or copy:

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

This is my code:

#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;
}

Aucun commentaire:

Enregistrer un commentaire