13

I have a function with a signature

void Foo(list<const A*>)

and I want to pass it a

list<A*>

How do I do this? (plz note - the list isn't constant, only the member of the list)

vondip
  • 13,809
  • 27
  • 100
  • 156

4 Answers4

19

The problem you have is that even though T * can be implicitly converted to a T const *, the template system isn't "aware" of that, so a whatever<T *> and whatever<T const *> are completely unrelated types, and there's no implicit conversion from one to the other.

To avoid the problem, I'd probably avoid passing a collection at all. Instead I'd have the function take a pair of iterators. A list<A *>::iterator can be implicitly converted to a list<A *>::const_iterator. For that matter, I'd probably make the function a template, so it can take iterators of arbitrary type.

This is likely to save you quite a bit of trouble -- a list is only rarely a good choice of container, so there's a very large chance that someday you'll want to change from list<A *> to vector<A *> or perhaps deque<A *> -- and if you make your function generic, you'll be able to do that without rewriting the function at all.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
0

You can just create a new list and populate it with the values from your original list. Perhaps not the most efficient solution as far as run-time and memory management is concerned, but certainly easy to code:

list<A*> list1;
list<const A*> list2;
for(list<A*>::iterator a=list1.begin(); a!=list1.end(); a++) list2.push_back(*a);
Josh
  • 148
  • 1
  • 11
0

You'll have to create a copy of the list - it's a pass-by-value argument. There's a fairly simple way to create a copy, since the element types have an implicit conversion: all STL containers can be created from a pair of iterators. So, in your case:

std::list<A*> src;
Foo(std::list<const A*>(src.begin(), src.end()));

This is slightly harder than it needs to be, because the STL represents ranges as pairs of iterators, and C++ conversion rules work on single objects.

Catskul
  • 17,916
  • 15
  • 84
  • 113
MSalters
  • 173,980
  • 10
  • 155
  • 350
-2

I believe you can pass it as it is. Remember that non-const types can be passed to something expecting a const type, but not the other way round!

Kunya
  • 26
  • 4