我需要在一个 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/