4

I got a function

void doSomething(list<A*> list1, list<A*> list2)

And classes

class B : A  
class C : A

Is there a direct way to call my function like

void doSomething(list<B*> listOfB, list<C*> listOfC)

or do I have to wrap it manually like

void doSomething(list<B*> listOfB, list<C*> listOfC) {
  list<A*> l1;
  list<A*> l2;

  for (B* b : listOfB)
    l1.insert(b);

  for (C* c : listOfC)
    l2.insert(c);

  doSomething(l1, l2); //calling the function taking supertype
}

I tried unsuccessfully to cast list<B*> to list<A*>, my guess is that due to template specialization, the compiler consider list<B*> and list<A*> unrelated, however B inherits A.

Can someone confirm this, or come with a different way to manage this problem ?

BЈовић
  • 62,405
  • 41
  • 173
  • 273
FloW
  • 97
  • 8

1 Answers1

4

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

Useless
  • 64,155
  • 6
  • 88
  • 132
  • Thanks to all for your quick answer, definitely useful. I think I'm gonna go for a function template, and look upon how to restrict the template type to a subclass of A. – FloW Jul 16 '14 at 09:33
  • 1
    You should be able to use `std::is_base_of` with either `enable_if` or `static_assert`. It's often useful to permit duck-typing though, even though the error messages aren't as good. – Useless Jul 16 '14 at 09:38
  • yes, I checked [this post](http://stackoverflow.com/questions/3175219/restrict-c-template-parameter-to-subclass) about it, thanks for it @Useless :) – FloW Jul 16 '14 at 13:46