vendredi 24 juin 2016

Create std::pair or std::map with std::unique_ptr as value implicitely

This code works in Visual Studio:

typedef struct {
    int a;
} data_t;

using datap_t = std::unique_ptr<data_t>;
using MyPair = std::pair<std::string, datap_t>;

int main() {
    data_t * pd1 = new data_t();
    MyPair p("tst", pd1); // This does not compile in gcc or clang
    // MyPair p2("tst", datap_t(pd1)); // This compiles

    return 0;
}

But clang and gcc give error:

error: no matching function for call to 'std::pair<const std::basic_string<char>, std::unique_ptr<data_t> >::pair(const char [3], data_t*&)

Here is the ideone to try.

The fact that I can datap_t(pd1) and it compiles means the constructor is valid, so why is that template does not find a suitable match?

I was looking to add a key-value pair to a map using emplace and that is why I wanted to have this implicit conversion in the first place. Note that like Visual Studio the implicit conversion works for most other types, such as std::string from "raw string".

This answere looks relevant, but it talks about a fixed bug and is very old.

Aucun commentaire:

Enregistrer un commentaire