Re: How to use static_cast for std::list of derived objects?
Javier Lopez wrote:
I would like to write a function with an std::list of a base class as
argument. I want to call this function making a cast of derived
classes
from this base class. How can use the static_cast to do that?
Here I show you some code that illustrates what I want to do.
[trivial code snipped]
void func(list<A>& a_list)
{
for (list<A>::iterator iter = a_list.begin() ; iter != a_list.end()
; iter++)
cout << iter->m_value << ' ';
cout << endl;
}
int main()
{
B b;
list<B> b_list;
for (int i=0 ; i<10 ; i++)
{
b.m_value = i;
b_list.push_back(b);
}
func((list<A>&)(b_list)); // Compile and works
func(reinterpret_cast<list<A>&>(b_list)); // Also compile and works
func(static_cast<list<A>&>(b_list)); // Does not compile (see below)
}
How about:
void func(const list<A*>& a_list);
int main()
{
list<B> b_list;
list<A*> a_list;
B b;
for (int i = 0; i < 10; ++i)
{
b.m_value = i;
b_list.push_back(b);
a_list.push_back(&(b_list.back()));
}
func(a_list);
}
Or better, following the STL spirit:
template <typename Itr>
void func(Itr begin, Itr end)
{
for (Itr i = begin; i != end; ++i)
cout << i->m_value << " ";
cout << endl;
}
int main()
{
list<B> b_list;
for ... // fill up b_list just like you did
func(b_list.begin(), b_list.end());
}
The last function call does not compile with gcc 4.1.1 and give me the
following output:
error: invalid static_cast from type 'std::list<B, std::allocator<B>
' to type 'std::list<A, std::allocator<A> >&'
Could someone explain me why?
Well, list<B> is not really a list<A>, neither is list<B*> a list<A*>.
Why? Because...
http://www.research.att.com/~bs/bs_faq2.html#conversion
Thank you very much in advance.
Ben
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]