I don't think anyone actually tried to answer the question of how to do the assignment of bb = aa;
As previously mentioned, you cannot define an implicit cast or assignment operator for std::list<B>
as a free operator. But you do have two options. Both of them rely on subclassing this collection... which is OK as long as you don't allow any additional state.
Option #1, is to define BB
as subclass of std::list<B>
and bb
would use these classes. (BB
would get an additional assignment operator.)
Option #2, is to use a helper class, and is likely closer to your original intent. The helper class would be defined like the BB
class described above, adding an implicit conversion operator back to std::list<B>
.
A complete example follows:
class A {};
class B: public A {
public:
B() = default;
B( const A &rhs ) {} // Empty because A and B are not defined with any state.
B& operator= ( const A &rhs ) { return *this; }
};
class BB : public std::list<B> {
public:
BB() = default;
BB(const std::list<A> &aa) { assign( aa.begin(), aa.end() ); }
BB& operator= ( const std::list<A> &rhs ) { assign(rhs.begin(), rhs.end()); return *this; }
operator std::list<B>() { return *this; }
};
// No new member variables or virtual methods are allowed.
static_assert( sizeof (std::list<B>) == sizeof (BB), "Bad derivation of std::list<B>" );
A a;
B b;
b = a; // works
std::list<A> aa;
std::list<B> bb;
BB helper;
bb = helper = aa; // Option #2; bb is std::list<B>
Or you could just use BB
directly:
BB bb = aa; // Option #1; use bb just like std::list<B>
std::list::assign(iter, iter)
instead of the copy-inserter pattern? – Monroemonroy