【问题标题】:Storing type information only of a class in std::vector仅在 std::vector 中存储类的类型信息
【发布时间】: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 的工厂。您可以在BC 上创建创建新对象的静态函数,并将函数指针存储在my_vector 中;或者为了获得更大的灵活性,您可以存储std::functions。
  • 您不能存储类型 - 故事结束。但是你可以存储函数指针,也许是 std::make_unique<B> 和 std::make_unique<C> 函数指针

标签: c++ c++17 c++20


【解决方案1】:

大概在找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;
    }
  }
}

【讨论】:

  • 然后,当你在所有的时候,考虑将my_vector 更改为std::(unordered_)map 而不是std::vector,然后D::addItem() 可以更有效地使用(unordered_)map::find() 而不是使用手动循环。
  • 雷米勒博感谢我会这样做的建议:)
猜你喜欢
  • 2020-05-21
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-30
相关资源
最近更新 更多