I would like to store an std::string
and something in an std::tuple
which is inside an std::vector
for creating std::unique_ptr
-s in runtime but not with an if/else
. I would like something like this:
class A { };
class B : public A { static const std::string name() { return "B"; } };
class C : public A { static const std::string name() { return "C"; } };
class D
{
public:
D();
void addItem(std:string name);
private:
std::vector<std::unique_ptr<A>> my_items;
std::vector<std::tuple<std::string, XXX something here XXX>> my_vector;
};
D::D()
{
my_vector.emplace_back(std::make_tuple(B::name(), YYY something here YYY));
my_vector.emplace_back(std::make_tuple(C::name(), YYY something here YYY));
}
void D::addItem(std::string name)
{
for (const auto &[typeName, YYY typeSomething YYY] : my_vector)
{
if (name == typeName)
{
my_items.emplace_back(std::make_unique<YYY typeSomething YYY>());
break;
}
}
}
I have tried typeid and std::type_info, std::type_index but that is not for my case I think.
CodePudding user response:
Probably looking for std::function
:
class D
{
public:
D();
void addItem(std:string name);
private:
std::vector<std::unique_ptr<A>> my_items;
std::vector<std::tuple<std::string, std::function<std::unique_ptr<A>()>>> my_vector;
};
D::D()
{
my_vector.emplace_back(std::make_tuple(B::name(), []{ return std::make_unique<B>(); }));
my_vector.emplace_back(std::make_tuple(C::name(), []{ return std::make_unique<C>(); }));
}
void D::addItem(std::string name)
{
for (const auto& [typeName, f] : my_vector)
{
if (name == typeName)
{
my_items.emplace_back(f());
break;
}
}
}