Re: want to pass vector<foo*> to fn expecting vector<const foo*>
On 2013-04-23 06:33, Balog Pal wrote:
On 4/22/2013 12:47 AM, Francis Glassborow wrote:
On 20/04/2013 22:49, Jonathan Thornburg wrote:
Martin Ba <0xcdcdcdcd@gmx.at> wrote:
But it's not clear to me that the reason (explained by Cline in
the first of those FAQ entries) *why* it's illegal to implicitly
convert foo** to const foo** should apply to converting
std::vector<foo*> to std::vector<const foo*> . That is, I don't
see any way in which allowing this implicit conversion would open
a hole in the type system. Can anyone clarify this point for me?
The problem is actually unrelated to issues with the safety of the
type system. The problem is with templates. These create unrelated
types. So there is no relationship in so far as the language
specification is concerned, between std::vector<foo *> and
std::vector<const foo *>
The same is true for auto_ptr<foo *> and auto_ptr<const foo *> (and
many other flavors), yet they are implicitly convertible.
Just to get this right: We are talking about conversions here, not
about reinterpretations, right? (These are what the Standard smart
pointers support) If so, I don't understand the concern here, because
it is really not so hard to convert std::vector<foo *> to
std::vector<const foo *> via the iterator-pair constructor, which
supports all implicit conversions, so we can already write
std::vector<foo *> vf = ..;
std::vector<const foo *> vcf(vf.begin(), vf.end());
There is currently work on a generalized "Range" concept (See the
upcoming revision of
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3513.html,
the new name will be "Traversable"), this would make such a conversion
slightly easier:
std::vector<foo *> vf = ..;
std::vector<const foo *> vcf(vf);
And it could be done too -- in my early collection class suite I
have IdxArr, that is essentially a vector of non-owning pointers
that looks like it had the objects. (and has all support to provide
filtered, sorted, etc views of real collections). The
implementation uses a non-template class storing void*s, and the
template part really has nothing but casts to make the pointers look
typed. The data and layout is shared. What makes reinterpret_casting
between collections fair game as long as the pointer types are
compatible enough.
Remember that the library grants support for user code to specialize
std::vector for any user-provided type within the template parameter
list. Such a specialization has no requirements that e.g. the order of
data members (not even the kind of data members) are the same as for
Library specialization.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]