Castling
Castling

Reputation: 1

C++ map with constructor and parameter

I want to have an unordered map with a string and a std::function that call a constructor a class to make a shared_ptr. But I'm stuck, I don't know what I should add as a second member of my map I've tried several things and I don't know what to do finally ...

#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
 
class A
{
public:
    A(const std::string &name){_name = name;}
    using Ptr = std::shared_ptr<A>;
private:
    std::string _name;
};

class BA : public A 
{
public:
    BA(const std::string &name) : A(name) {}
    using Ptr = std::shared_ptr<BA>;
};

class BB : public A 
{
public:
    BB(const std::string &name) : A(name) {}
    using Ptr = std::shared_ptr<BB>;
};

int main()
{
    static const std::unordered_map<std::string, std::function<A::Ptr(const std::string &)>> mapStringConstructor
    {
        {"A", A::A(const std::string &)},
        {"BA", BA::BA(const std::string &)},
        {"BB", BB::BB(const std::string &)}
    };
    return 0;
}

Thank in advance,

Upvotes: 0

Views: 789

Answers (1)

David G
David G

Reputation: 96800

You may just want to pass a lambda instead:

static const std::unordered_map<std::string, std::function<A::Ptr(const std::string&)>> mapStringConstructor{
    {"A",  [](const std::string& str) { return std::make_shared<A>(str); }},
    {"BA", [](const std::string& str) { return std::make_shared<BA>(str); }},
    {"BB", [](const std::string& str) { return std::make_shared<BB>(str); }}};

To use a function template, do this:

template<class T>
std::shared_ptr<T> make_class(const std::string& str) {
  return std::make_shared<T>(str);
}

static const std::unordered_map<std::string, std::function<A::Ptr(const std::string&)>> mapStringConstructor{
        {"A",  make_class<A>},
        {"BA", make_class<BA>},
        {"BB", make_class<BB>}};

Upvotes: 1

Related Questions