2

I am trying to initialize the class FileList, which extends std::map as a collection of FileInfo objects with a map specific initializer list but I receive the following error:

Error C2440 'initializing': cannot convert from 'initializer list' to 'FileList'

#include <string>
#include <map>

class FileInfo
{
public:
    FileInfo(const std::string &name) : mName(name) { }

    std::string operator () () const
    {
        return mName;
    }

private:
    std::string mName;
};

class FileList : public std::map<std::string, FileInfo> { };

int main(int argc, char *argv[])
{
    FileInfo f1 = { "f1" };
    FileInfo f2 = { "f2" };
    FileList fileList{ { f1(), f1 }, { f2(), f2 } };

    return 0;
}

I didn't find out why this fails, given the fact that FileList it's exactly a std::map.

Is there a possibility to pass the initializer list to the std::map inherited by FileList without inserting manually each object like below?

FileList fileList;
fileList[f1()] = f1;
fileList[f2()] = f2;

EDIT:

As @DeiDei says, it is not recommended to derive from an std::container.

Alexandru Irimiea
  • 2,513
  • 4
  • 26
  • 46
  • 3
    Constructors aren't inherited by default. Look up inheriting constructors. Also, please don't derive from an std::container. It won't work out fine. – DeiDei Dec 27 '16 at 09:18
  • 1
    If you want the type to be *exactly* a map, you can do `using FileList = std::map;`. – Bo Persson Dec 27 '16 at 09:21
  • @DeiDei I didn't know it's not recommended to extend STL containers, now I found out the main reason why: "he main reason for not inheriting from std::vector publicitly is an absence of virtual destructor" [http://stackoverflow.com/a/4357417/4806882](http://stackoverflow.com/a/4357417/4806882) – Alexandru Irimiea Dec 27 '16 at 20:35

1 Answers1

3

constructors in derived class are not inherited from base class by default you need to do it manually.

class FileList : public std::map<std::string, FileInfo> 
{
    using std::map<std::string, FileInfo>::map;
};

Please note that it's not a good idea to inherit from stl containters.

It's better to just do:

using FileList = std::map<std::string, FileInfo>;
paweldac
  • 1,144
  • 6
  • 11