c++ - 设计模式,对象的 vector ,每一种都有两种可能的类型

标签 c++ design-patterns vector polymorphism

我需要在一个 vector 中存储恰好两种类型的对象,这两种类型几乎没有共同点。

将它们存储在 vector 中后,我想遍历该 vector 并根据类型执行操作。

到目前为止我的想法:

  • 多态性。矫枉过正,对我帮助不大,因为我可能会这样做:

    if(dynamic_cast<T1>() != nullptr) {
        ...
    } else {
       ...
    }
    
  • 合并两种类型(方法和字段)并添加一个 bool 值,表示它的类型是 1 还是 2。

这两种模式对我来说都显得十分笨拙,可能有一个完全简单的解决方案,但我根本看不到。

第一种是这样的:

struct PatternMatch {
  int length;
  int indexInDict;
}

第二个 一:

struct NoMatch {
  std::string rawChars;
}

最佳答案

使用boost::variant或任何其他“基于堆栈的可区分 union 容器”。我还建议 visiting the variant using lambdas .

// Either `A` or `B`.
using my_type = boost::variant<A, B>;

std::vector<my_type> my_vec;

// ...`emplace_back` stuff into `my_vec`...

auto visitor = make_lambda_visitor<void>(
    [](A&) { /* do something with A */ },
    [](B&) { /* do something with B */ }
);

for(auto& x : my_vec)
{
     boost::apply_visitor(visitor, x);
}

注意 C++17 将有 std::variant .

关于c++ - 设计模式,对象的 vector ,每一种都有两种可能的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39179906/

相关文章:

c++ - Metal - 针对内存延迟优化 GPU 矩阵乘法

c++ - Visual Studio 控制台应用程序调试

c++ - 如何在预编译后通过查看文件来调试Boost?

java - 为 Java 表达式求值器提供通用实现

design-patterns - 何时使用桥接模式以及它与适配器模式有何不同?

c++ - 对一对 vector 进行排序

c++ - 为什么调用析构函数

c - Realloc:结构动态 vector 中的下一个大小无效

c++ - 如何修改给定的类以使用 const 运算符

java - 望远镜构造函数的设计模式或依赖注入(inject)