vondip vondip - 1 year ago 75
C++ Question

C++ How do I pass a list of non-consts to a function wanting a list of consts

I have a function with a signature

void Foo(list<const A*>)

and I want to pass it a


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download