pointerdk
pointerdk

Reputation: 11

Insert custom class with template into std::map

I have written my own class and I want to insert it into a map. See the example below:

#include <iostream>
#include <string>
#include <map>
#include <memory>
#include <mutex>

template <class T>
class A {
public:
    T a;
    A() = default;
    ~A() = default;
    A(T i) { a = i; }
};

int main()
{
  std::pair<int,A<int>> p;
  p = std::make_pair<int,A<int>>(9,A<int>(1));

  std::map<int, A<int>> m;
  m.emplace(1,A<int>(1));
}

When I try to compile this, I get an enormous error. Please help interpret it. :)

See error here: http://cpp.sh/9nc35

EDIT: I had the typo, thanks! Though, the other problem I was struggling with first arose now. Seems like it is because of the mutex? Why?

Upvotes: 1

Views: 528

Answers (2)

Dan M.
Dan M.

Reputation: 4052

You are trying to insert/emplace pair (pair<...>, A) into your map, while you've specified it's key as an int. You most-likely want m.emplace(9,std::make_unique<A<int>>(1)); (see 9 instead of p) or just m.insert(p); (would work fine in your cpp.sh).

Furthermore, your use of unique_ptr here is most-likely wrong/unwarranted and only complicates things. See fixed up example here: http://cpp.sh/3d2hw

Also, you may study STL collections/see some basic examples over at https://en.cppreference.com (https://en.cppreference.com/w/cpp/container/map/map for some map construction examples).

Upvotes: 0

Karl Nicoll
Karl Nicoll

Reputation: 16439

Your map is defined as:

std::map<int, std::unique_ptr<A<int>>>

But in the next line you're trying to pass an std::pair<int, A<int>> to m.emplace() as the key.

I think you just want to do:

m.emplace(9, std::make_unique<A<int>>(1));
//        ^
//        Not `p`

Upvotes: 2

Related Questions