cast list to list where B inherits A

后端 未结 1 1450
轮回少年
轮回少年 2020-12-21 04:52

I got a function

void doSomething(list list1, list list2)

And classes

class B : A  
class C : A


        
相关标签:
1条回答
  • 2020-12-21 05:09

    Your intuition (and juanchopanza's comment) is correct - the lists are completely unrelated types.

    The options are:

    1. use list<A*> everywhere in the first place, even when you know the dynamic type is B* or C*
    2. write a wrapper over list<A*> which casts to/from the correct dynamic type - this is equivalent to the (un)boxing behaviour in Java generics
    3. re-write doSomething as a function template whose only constraint is that the types be convertible

      template <typename Sequence1, typename Sequence2>
      void doSomething(Sequence1 &x, Sequence2 &y) {
        // require only that *x.begin() is convertible with *y.begin(), etc.
      }
      

      I'd also agree with Kerrek's suggestion that this should use iterators instead, but that doesn't change the type requirement significantly - you just get two iterator type params instead of two container type params

    0 讨论(0)
提交回复
热议问题