0

I am trying to write a class that inherits the std::map but I also want to overload one specific function while keeping the remaining inherited functions available for use. After reading a bit about that it seems you have to use the namespace of map to be able to use it's functions. However I had to use using std::map<K,V>::map; for it to be working. My question is what is the last ::map? Is it the name of the namespace of map? But if we take cout for example you simply needed using cout;. Also how does one know the name of the namespaces i stl?

The code looks something like this:

#include <map>

template<typename K,typename V>
class my_map : public std::map<K,V>
{   
private:
    /* data */ 
public:
    using std::map<K,V>::map;
};

Sekai
  • 15
  • 5
  • 2
    `using Base::Base;` is called [inheriting constructors](https://en.cppreference.com/w/cpp/language/using_declaration#Inheriting_constructors). – François Andrieux Aug 13 '20 at 20:05
  • 4
    Beware that [publicly inheriting from standard types can cause problems](https://stackoverflow.com/questions/6806173/subclass-inherit-standard-containers). It *can* work but you have to be careful because they weren't designed to be derived from. – François Andrieux Aug 13 '20 at 20:06
  • Good tip, I will watch out for that! :) – Sekai Aug 13 '20 at 20:36

1 Answers1

1
using std::map<K,V>::map;

You need to use it if u want to use the base ctors outside the class (to inherit the constructors).

And this std::map<K,V>::map is the constructor and qualified by the class name.

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • 3
    I'm not sure what the correct terminology is. Because `using T::T;` works even if `T` doesn't have a default constructor. So it can't be naming or referring to a constructor. It is just a special case for a `using` declaration, as far as I know. – François Andrieux Aug 13 '20 at 20:12
  • @FrançoisAndrieux agreed. – asmmo Aug 13 '20 at 20:13
  • 1
    [The standard](https://timsong-cpp.github.io/cppwp/namespace.udecl#1) uses "names a constructor" so I suppose that is allowed after all. I guess you can put it back the way it was. – François Andrieux Aug 13 '20 at 20:14
  • Aha, so it's the constructor! I got it. Would this inherit all the member functions in map as well? Or how would I otherwise gain access to its member functions? – Sekai Aug 13 '20 at 20:34
  • 1
    @Sekai Since your inheritance is `public` all the `public` members of the base class are already inherited. – François Andrieux Aug 13 '20 at 20:37
  • @FrançoisAndrieux Yea it most likely is an exception I guess. – Sekai Aug 13 '20 at 20:39
  • 1
    @Sekai the ctors are exception. you can access the rest functions as the following. `my_map my_map_obj; my_map_obj.insert({2,2});` – asmmo Aug 13 '20 at 20:41
  • @FrançoisAndrieux Oh I understand. Thanks a bunch for explaining! :D – Sekai Aug 13 '20 at 20:41