开发者

C++ container class type conversion

开发者 https://www.devze.com 2023-01-07 22:28 出处:网络
Say, i got Set<DerivedClass*> set1; and i got Set<BaseClass*> set2; how do i do t开发者_运维技巧his?

Say, i got

Set<DerivedClass*> set1;

and i got

Set<BaseClass*> set2;

how do i do t开发者_运维技巧his?

Set<BaseClass*> set3 = set1.substract(set2); //static cast!


Try set_difference


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消