vendredi 15 mai 2020

std::map emplace non-movable non-copyable non-default-constructible type

I want a map of a class that has no copy ctor, no move ctor, and no default ctor (I have no control over this class).

I've tried using std::map::emplace with the std::piecewise_construct and std::forward_as_tuple arguments, but it seems like the compiler is telling me that this is not possible because it tries default constructing first.

// Example program
#include <iostream>
#include <string>
#include <map>
#include <utility>
#include <tuple>

class stone
{
public:
    stone() = delete;
    stone(stone& s) = delete;
    stone(stone&& s) = delete;
    stone(const std::string& s) : str(s)
    {
    }
    std::string str;
};

int main()
{
    std::map<int, stone> m;
    m.emplace(std::piecewise_construct, std::forward_as_tuple(5), std::forward_as_tuple("asdf"));
    std::cout << "map[5]: " << m[5].str << "\n";
}

See the example with the compiler error here: http://cpp.sh/8bbwh

How can I make this work? I've tried looking at similar questions, but they don't seem to contain any answers that are useful to my very specific scenario.

Aucun commentaire:

Enregistrer un commentaire