How to make my private class visible to STD containers?

This is the code:

#include <map>
class Hidden {
private:
  friend class Visible;
  Hidden(); { /* nothing */ }
};
class Visible {
public:
  void f() {
    std::map<int, Hidden> m;
    m[1] = Hidden(); // compilation error, class Hidden is private
  }
};

The code does not compile because the constructor of the class Hiddenis private to the class std::map. Obviously, I don't want the class to std::mapbe a friend Hidden. But what am I to do here? Thanks in advance!

+3
source share
2 answers

Add a map as a friend class:

#include <map>
class Hidden {
private:
  friend class Visible;
  friend class std::map<int, Hidden> ;
  Hidden() {}
};
class Visible {
public:
  void f() {
    std::map<int, Hidden> m;
    m[1] = Hidden(); // compilation error, class Hidden is private
  }
};

Of course, this means that you must declare all hidden users inside Hidden, but this is exactly the part of the "private class" template that you use ...

+2
source

For your Hidden class, a map is another class, and unless you explicitly make the map a friend of Hidden, it will not be able to access the hidden constructor.

, paercebal, , Hidden.

0

Source: https://habr.com/ru/post/1753990/


All Articles