C++容器类类型转换

发布于 2024-09-10 03:41:24 字数 246 浏览 1 评论 0原文

说,我得到了

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

潜移默化 2024-09-17 03:41:24

使用

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.

空城旧梦 2024-09-17 03:41:24

您可以创建类似 static_pointer_cast。即,您需要独立的模板,该模板可以执行从一个 Set 专业化到另一个专业化的 static_cast

You could create something like static_pointer_cast. i.e. you need stand-along template which could perform static_cast from one Set specialization to another.

哑剧 2024-09-17 03:41:24

如果您想将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文