【发布时间】:2022-08-17 03:24:22
【问题描述】:
我想存储一个std::string 和某物在std::tuple 中,它位于std::vector 中,用于在运行时创建std::unique_ptr-s,但不使用if/else。我想要这样的东西:
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;
}
}
}
我已经尝试过 typeid 和 std::type_info, std::type_index 但我认为这不适合我的情况。
-
工厂模式?因为
YYY实际上是As 的工厂。您可以在B和C上创建创建新对象的静态函数,并将函数指针存储在my_vector中;或者为了获得更大的灵活性,您可以存储std::functions。 -
您不能存储类型 - 故事结束。但是你可以存储函数指针,也许是 std::make_unique<B> 和 std::make_unique<C> 函数指针