C++容器类类型转换
说,我得到了
Set<DerivedClass*> set1;
,我得到了,
Set<BaseClass*> set2;
我该怎么做?
Set<BaseClass*> set3 = set1.substract(set2); //static cast!
Say, i got
Set<DerivedClass*> set1;
and i got
Set<BaseClass*> set2;
how do i do this?
Set<BaseClass*> set3 = set1.substract(set2); //static cast!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试 set_difference
Try set_difference
使用
http ://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/algorithms/set/set_difference.html
但是,您必须使用第二个并提供您自己的二进制文件谓词。默认谓词运算符<将比较指针。你可能想做的是比较
值,因此需要提供您自己的谓词。
Use
http://www.boost.org/doc/libs/1_43_0/libs/range/doc/html/range/reference/algorithms/set/set_difference.html
However you must use the second one and provide your own binary predicate. The default predicate operator< will compare the pointers. What you probably want to do is compare
the values and thus need to provide your own predicate.
您可以创建类似
static_pointer_cast
。即,您需要独立的模板,该模板可以执行从一个Set
专业化到另一个专业化的static_cast
。You could create something like
static_pointer_cast
. i.e. you need stand-along template which could performstatic_cast
from oneSet
specialization to another.如果您想将 set2 转换为与 set1 相同的类型,我强烈建议您不要这样做。只要 substract 不修改其参数,您就可能会使用reinterpret_cast,但这是一个非常坏主意。
您真正需要的是一个非成员函数,正如 Dave18 所说,您可能需要 std::set_difference 函数 - 除非您会遇到迭代器类型不匹配的问题。
一种解决方案是开发您自己的“适配器”迭代器类,该类主要将调用传递给原始迭代器,但在取消引用时执行所需的转换。
比编写自己的迭代器适配器更好的是重用别人的迭代器适配器。我认为 boost::iterator_adaptor 看起来可能的候选人,尽管我还没有正确检查。
If you want to cast set2 to the same type as set1, I strongly recommend you don't. You might get away with a reinterpret_cast so long as substract doesn't modify its parameter, but it's a very bad idea.
What you really need is a non-member function and, as Dave18 says, you probably want the std::set_difference function - except that you'll have problems with mismatched iterator types.
One solution to that is to develop your own "adaptor" iterator class, which mostly passes calls through to the original iterator, but when dereferenced does the needed cast.
Better than writing your own iterator adaptors is reusing someone elses. I think boost::iterator_adaptor looks a likely candidate, though I haven't checked properly.