I'm trying to create my own translator. It's university work. I need an iterator in my class Translator.
class Translator
{
private:
map <string,Word> translator;
public:
class iterator
{
friend class Translator;
private:
map<string,Word>::iterator itm;
public:
iterator operator++();
pair <string,Word> &operator*();
bool operator==(const iterator &it)const;
};
};
I'm trying to overload operator*();
This is the code.
pair <string, Word>& Translator::iterator::operator*()
{
return (*itm);
}
Error:
invalid initialization of reference of type ‘std::pair<std::basic_string<char>, Word>&’ from expression of type ‘std::pair<const std::basic_string<char>, Word>
The keys of a map are constant, so the value type is pair<const string, Word>.
Some type aliases might make the code friendlier:
typedef map <string,Word> map_type;
typedef map_type::value_type value_type;
value_type &operator*();
It is more a complement than an actual answer but if you want a nice iterator (STL complient) you will also need to add several typedefs, to say for instance the type of your iterator (in your case you have an input iterator). Then you can use your iterator with any stl algorithm which can be very nice. However this can be quite cumbersome.
A very nice approach is using boost facade iterators, you just need to rewrite what is needed that is three methods for an input iterator that specify how to increment, test if two iterators are equals and dereference. Boost is then doing all the dirty work for you and you can then use all stl algorithms with your standard compliant iterators.
Here is an example from the link I gave you :
# include <boost/iterator/iterator_facade.hpp>
# include "node.hpp"
class node_iterator : public boost::iterator_facade<
node_iterator
, node_base
, boost::forward_traversal_tag
>{
public:
node_iterator()
: m_node(0) {}
explicit node_iterator(node_base* p)
: m_node(p) {}
private:
friend class boost::iterator_core_access;
void increment() { m_node = m_node->next(); }
bool equal(node_iterator const& other) const
{
return this->m_node == other.m_node;
}
node_base& dereference() const { return *m_node; }
node_base* m_node;
};
Related
Right now, I have a class that can satisfy an API requirement with a random-access iterator. However, I can envision a situation where the implementation will change and only a forward iterator can be provided.
Therefore, I would like to restrict callers from using the random-access functionality. I know I can write my own implementation (e.g. restricted_bar_iterator), but was wondering if there is anything simpler (i.e. requiring less coding).
class BAR { ... };
class FOO {
public:
// Bad...clients may expect 'bar_iterator' to be random access...
typedef std::vector<BAR>::iterator bar_iterator;
bar_iterator begin_bar() const;
bar_iterator end_bar() const;
// Possible solution here!
class restricted_bar_iterator :
public std::iterator< std::forward_iterator_tag, BAR > { ... };
};
void baz()
{
FOO foo;
bar_iterator it = foo.begin_bar() + 5; // want a compile time error here!
}
Here's an example using Boost Iterator Adaptor. I used int instead of BAR.
#include <boost/iterator/iterator_adaptor.hpp>
#include <vector>
struct iterator :
public boost::iterator_adaptor<
iterator, // the name of our class, see docs for details
std::vector<int>::iterator, // underlying base iterator
boost::use_default, // for value type
boost::forward_traversal_tag // all the boilerplate for this!
>
{
// need this to convert from vector::iterator to ours
explicit iterator(std::vector<int>::iterator i)
: iterator::iterator_adaptor_(i) {}
};
int main()
{
std::vector<int> v;
iterator it(v.begin());
++it; // OK
it += 1; // ERROR
}
This effectively uses a std::vector<T>::iterator as a base class, but only allows operations that are defined for forward iterators. The downside are the error messages - they aren't very pretty.
You definitely have to do some coding, but you might be able to inherit from the underlying type to get most of the functionality, just overriding the operations you don't want to work, either by defining them as deleted in C++11 or making them private and unimplemented in C++03:
class FOO {
// Bad...clients may expect 'bar_iterator' to be random access...
typedef std::vector<BAR>::iterator bar_iterator_impl;
public:
// Possible solution here!
struct bar_iterator : bar_iterator_impl {
bar_iterator& operator++() {
++static_cast<bar_iterator_impl&>(*this);
return *this;
}
bar_iterator operator++(int) {
bar_iterator copy(*this);
++*this;
return copy;
}
typedef std::forward_iterator_tag iterator_category;
typedef std::iterator_traits<bar_iterator_impl>::value_type value_type;
typedef std::iterator_traits<bar_iterator_impl>::difference_type difference_type;
typedef std::iterator_traits<bar_iterator_impl>::pointer pointer;
typedef std::iterator_traits<bar_iterator_impl>::reference reference;
private:
friend void operator+(bar_iterator const&, long);
friend void operator+(long, bar_iterator const&);
friend void operator-(bar_iterator const&, long);
friend void operator-(long, bar_iterator const&);
};
bar_iterator begin_bar() const;
bar_iterator end_bar() const;
};
However this only works if std::vector<BAR>::iterator is a class type, and it could be a pointer, in which case it cannot be derived from. To be portable, you'd need to define the whole iterator API yourself.
I'm writing an own container class and have run into a problem I can't get my head around. Here's the bare-bone sample that shows the problem.
It consists of a container class and two test classes: one test class using a std:vector which compiles nicely and the second test class which tries to use my own container class in exact the same way but fails miserably to compile.
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
template <typename T>
class MyContainer
{
public:
class iterator
{
public:
typedef iterator self_type;
inline iterator() { }
};
class const_iterator
{
public:
typedef const_iterator self_type;
inline const_iterator() { }
};
iterator begin() {
return iterator();
}
const_iterator begin() const {
return const_iterator();
}
};
// This one compiles ok, using std::vector
class TestClassVector
{
public:
void test() {
vector<int>::const_iterator I=myc.begin();
}
private:
vector<int> myc;
};
// this one fails to compile. Why?
class TestClassMyContainer
{
public:
void test(){
MyContainer<int>::const_iterator I=myc.begin();
}
private:
MyContainer<int> myc;
};
int main(int argc, char ** argv)
{
return 0;
}
gcc tells me:
test2.C: In member function ‘void TestClassMyContainer::test()’:
test2.C:51: error: conversion from ‘MyContainer::iterator’ to non-scalar type ‘MyContainer::const_iterator’ requested
I'm not sure where and why the compiler wants to convert an iterator to a const_iterator for my own class but not for the STL vector class. What am I doing wrong?
When you call begin() the compiler by default creates a call to the non-const begin(). Since myc isn't const, it has no way of knowing you mean to use the const begin() rather than the non-const begin().
The STL iterator contains a cast operator which allows an iterator to be silently converted to a const_iterator. If you want this to work you need to add one as well like so:
class iterator
{
public:
typedef iterator self_type;
inline iterator() { }
operator const_iterator() { return const_iterator(); }
};
or allow const_iterator to be constructed from an iterator like so:
class const_iterator
{
public:
typedef const_iterator self_type;
const_iterator(iterator& ) {}
inline const_iterator() { }
};
You should have a look to the Boost.Iterators library, especially the iterator_facade and iterator_adaptor sections. They contain a build-up of an iterator "from scratch".
It will show you how to write iterators without too much duplication, because most of the times the code the const and non-const versions is about the same, apart from the const qualification itself. Using templates it's possible to write it once, then declare two different types, and that's what the library documentation illustrates.
In containers iterator type must be convertible to const_iterator. It is needed for the cases where you iterate through a mutable container using a non-mutable (const) iterator as this makes perfect sense. In your case myc is mutable (non-const), but you create a const iterator on that.
I have to work with an application in C++ similar to a phone book: the class Agenda with an STL list of Contacts.Regarding the contacts hierarchy,there is a base-class named Contact(an abstract one),and the derived classes Friend and Acquaintance(the types of contact).
These classes have,for instance, a virtual method called getName,which returns the name of the contact.
Now I must implement the Composite pattern by adding another type of contact,Company(being derived from Contact),which also contains a collection of Contacts(an STL list as well),that can be either of the "leaf" type(Friends or Acquaintances),or they can be Companies as well.
Therefore,Company is the Compound type.
The question is: how and where can I implement an STL find_if to search the contact with a given name(via getName function or suggest me smth else) both among the "leaf"-type Contact and inside the Company collection?
In other words,how do I traverse the tree in order to find possible matches there too,using an uniform function definition?
I hope I was pretty clear...
Well, one way to do it:
virtual contact* contact::findContact(std::string name)
{
if(m_name == name) {return this;}
return NULL;
}
Then:
contact * Company::findContact(std::string name)
{
if(!contact::findContact(name) )
{
//For each contact in the contact list, findContact(name)
//If we find something, return that.
//Otherwise return null.
}
return this;
}
What you're doing is asking each node to find the one you're looking for, without caring what type of node (leaf or otherwise) it is. Each node then checks itself, and, for those with child nodes, their children.
List is the wrong type for a large type of contacts since you might have a O(N) to find the last contact or even to find no contact.
I suggest you to use a hash map (unordered_map from boost/tr1) or a regular map so you will be able to find them by ID or their name using a key.
Also sounds like a company should just be a tree of contacts.
You can find tree implementations here.
You transvase through the tree to find the node you need.
"Now I must implement the Composite pattern by adding another type of contact,Company(being derived from Contact),which also contains a collection of Contacts(an STL list as well),that can be either of the "leaf" type(Friends or Acquaintances),or they can be Companies as well"
You could create a stl-compatible composite iterator for Company.
class Company : public Contact {
std::list<Contact *> contactList;
//snip...other private members
friend class CompanyIterator;
friend class ConstCompanyIterator;
public:
// nested iterator classes
class CompanyIterator : public std::iterator<std::forward_iterator_tag, Contact *> {
friend class Company;
// pair<>.first is the iterator obtain by calling begin()
// pair<>.second is the end iterator
std::stack< std::pair< std::list<Contact *>::iterator,
std::list<Contact *>::iterator> > iters_stack;
Contact *pCurrentContact;
Company *pCompany; // This is the top level company which will be iterated.
public:
explicit CompanyIterator(Company &c);
// Required forward iterator methods follow
CompanyIterator();
CompanyIterator(const CompanyIterator&);
CompanyIterator& operator=(const CompanyIterator& other);
Contact &operator*() const;
Contact *operator->() const;
CompanyIterator& operator++();
CompanyIterator operator++(int);
bool operator==(const CompanyIterator& x) const;
bool operator!=(const CompanyIterator& x) const;
};
// nested iterator class
class ConstCompanyIterator : public std::iterator<std::forward_iterator_tag,
const Contact *> {
friend class Company;
// We use CompanyIterator to implement ConstCompanyIteraor
CompanyIterator inner_iter; // fwd operations here,
// using "const_cast<Company *>(this)->method()"
public:
explicit ConstCompanyIterator(const Company & dir);
// This ctor will function as a cast operator, to convert a CompanyIterator
// into a ConstCompanyIterator
ConstCompanyIterator(const CompanyIterator &iter);
// Required forward iterator methods follow
ConstCompanyIterator();
ConstCompanyIterator(const ConstCompanyIterator&);
ConstCompanyIterator& operator=(const ConstCompanyIterator& other);
const Contact &operator*() const;
const Contact *operator->() const;
ConstCompanyIterator& operator++();
ConstCompanyIterator operator++(int);
bool operator==(const ConstCompanyIterator& x) const;
bool operator!=(const ConstCompanyIterator& x) const;
};
typedef CompanyIterator iterator;
typedef ConstCompanyIterator const_iterator;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
// snip... other Company public methods
};
For the implementation of the forward iterator methods given above, see the Composite Iterator code on Github. Most of the implementation is in Directory.cpp. The github code is for composite pattern that models a file system. Class Directory is the composite. Class File is the leaf class. Class Node is the base component class.
The functor for find_if would look like
FindIfFunctor {
std::string name;
public:
FindIfFunctor(const std::string& n) : name(n) {}
bool operator()(const Contact& c) { return c.getName().compare(name); }
};
Finally, the find_if code
Company c;
// snip... stuff gets added to company
string someName("IBM");
find_if(c.begin(), c.end(), FindIfFunctor(someName));
I'd like to design a class Foo that stores various data of different types and returns iterators over them. It's supposed to be generic, so the user of Foo does not know how the data is stored (Foo could be using std::set or std::vector or whatever).
I'm tempted to write an interface like this:
class Foo {
class FooImpl;
FooImpl* impl_;
public:
const Iterator<std::string>& GetStrings() const;
const Iterator<int>& GetInts() const;
};
where Iterator is something like this (like iterators in .NET):
template<class T>
class Iterator {
public:
const T& Value() const = 0;
bool Done() const = 0;
void Next() = 0;
};
But I know that kind of iterator is not standard in C++, and it's better to use iterators the way the STL does, so you can use the STL algorithms on them.
How can I do that? (Do I need iterator_traits by any chance?)
Do you understand why the STL chose to put iterator implementation details in the header file? JIT frameworks are able to inline across compilation units, but C++ can only inline within a compilation unit. Advancing through a sequence is much faster when inlined, the cost of a function call dominates actually traversing the data structure.
If you really want to hide the implementation details, go ahead. You could make an STL-compatible iterator that implements operator++ and operator!= and operator-> in terms of protected virtual functions, the Next, Done, and Value you've mentioned would be decent names. Just expect to pay for the encapsulation with lower performance.
A c++ class with iterators has to provide at least two functions if they have to work with the std library
iterator begin() //returns an iterator at starting pos
iterator end() //returns an iterator one past end or just invald
The iterator has to overload the increment operators, equals and *
iterator operator++()
iterator operator==()//make sure that an invalid iterator equals end()
T& operator*()
You can use the iterator class to wrap around the iterator of the internal storage to ensure that the user is limited to these methods.
template <typename T> iter
{
iter(T::iterator& intern)
T::value_type& operator*(){return *intern}
iter operator++(){return iter(++intern);}
bool operator==(iter const& other)const{return intern == other.intern;}
}
Where T is the type of your container.(The class is incomplete and I may have mixed something up)
It almost looks like you're trying to create container-independent code, which is not (in general) a good idea, unless you are writing an algorithm which can operate solely with iterators. (See Scott Myers Effective STL Item 2: Beware the illusion of container-independent code)
The problem is that most of the standard containers do not provide overlapping functionality. If you're writing code for a particular container, assume you're writing code for that container. Don't bother trying to make it container-independent.
Use a typedef to return an boost::iterator_range. For example (never mind the names),
class Container
{
typedef std::vector<int> Collection;
public:
typedef boost::iterator_range<Collection::iterator> CollectionRange;
typedef Collection::iterator CollectionIterator;
Range range() const {
return make_iterator_range(collection_.begin(), collection_.end());
}
private:
Collection collection_;
};
The user code will be
Container c;
// ...
FOREACH(int i, c.range()) { //... }
Container::Range r = c.range();
for(Container::iterator j = r.begin(); j!= r.end(); j++) { // ... }
This is not generic, but the same idea can be used with templates.
To fulfill the requirement that the particular container (vector, set, ...) is not mentioned in the header file, and the user will be able to iterate over all strings, is to use the visitor pattern. The downside, of course, is that the user won't be able to use the STL algorithms on the strings.
// foo.h
class StringVisitor {
public:
void accept(const std::string& str) {
std::cout << str << std::endl;
}
};
class Foo {
class Impl;
Impl* impl_;
public:
Foo();
~Foo();
void VisitStrings(StringVisitor v) const;
};
// foo.cc
class Foo::Impl {
typedef std::vector<std::string> StringContainer;
StringContainer str_;
public:
Impl() {
str_.push_back("a");
str_.push_back("b");
}
void VisitStrings(StringVisitor v) const {
for(StringContainer::const_iterator it = str_.begin();
it != str_.end(); ++it){
v.accept(*it);
}
}
};
Foo::Foo() : impl_(new Impl()) {}
Foo::~Foo() {delete impl_;}
void Foo::VisitStrings(StringVisitor v) const {
impl_->VisitStrings(v);
}
// main.cc
int main() {
Foo foo;
foo.VisitStrings(StringVisitor());
return 0;
}
Having toyed with this I suspect it isn't remotely possible, but I thought I'd ask the experts. I have the following C++ code:
class IInterface
{
virtual void SomeMethod() = 0;
};
class Object
{
IInterface* GetInterface() { ... }
};
class Container
{
private:
struct Item
{
Object* pObject;
[... other members ...]
};
std::list<Item> m_items;
};
I want to add these methods to Container:
MagicIterator<IInterface*> Begin();
MagicIterator<IInterface*> End();
In order that callers can write:
Container c = [...]
for (MagicIterator<IInterface*> i = c.Begin(); i != c.End(); i++)
{
IInterface* pItf = *i;
[...]
}
So essentially I want to provide a class which appears to be iterating over some collection (which the caller of Begin() and End() is not allowed to see) of IInterface pointers, but which is actually iterating over a collection of pointers to other objects (private to the Container class) which can be converted into IInterface pointers.
A few key points:
MagicIterator is to be defined outside Container.
Container::Item must remain private.
MagicIterator has to iterate over IInterface pointers, despite the fact that Container holds a std::list<Container::Item>. Container::Item contains an Object*, and Object can be used to fetch IInterface*.
MagicIterator has to be reusable with several classes which resemble Container, but might internally have different list implementations holding different objects (std::vector<SomeOtherItem>, mylist<YetAnotherItem>) and with IInterface* obtained in a different manner each time.
MagicIterator should not contain container-specific code, though it may delegate to classes which do, provided such delegation is not hard coded to to particular containers inside MagicIterator (so is somehow resolved automatically by the compiler, for example).
The solution must compile under Visual C++ without use of other libraries (such as boost) which would require a license agreement from their authors.
Also, iteration may not allocate any heap memory (so no new() or malloc() at any stage), and no memcpy().
Thanks for your time, even if you're just reading; this one's really been bugging me!
Update: Whilst I've had some very interesting answers, none have met all the above requirements yet. Notably the tricky areas are i) decoupling MagicIterator from Container somehow (default template arguments don't cut it), and ii) avoiding heap allocation; but I'm really after a solution which covers all of the above bullets.
I think you have two separate issues here:
First, create an iterator that will return the IInterface* from your list<Container::Item>. This is easily done with boost::iterator_adaptor:
class cont_iter
: public boost::iterator_adaptor<
cont_iter // Derived
, std::list<Container::Item>::iterator // Base
, IInterface* // Value
, boost::forward_traversal_tag // CategoryOrTraversal
, IInterface* // Reference :)
>
{
public:
cont_iter()
: cont_iter::iterator_adaptor_() {}
explicit cont_iter(const cont_iter::iterator_adaptor_::base_type& p)
: cont_iter::iterator_adaptor_(p) {}
private:
friend class boost::iterator_core_access;
IInterface* dereference() { return this->base()->pObject->GetInterface(); }
};
You would create this type as inner in Container and return in from its begin() and end() methods.
Second, you want the runtime-polymorphic MagicIterator. This is exactly what any_iterator does. the MagicIterator<IInterface*> is just any_iterator<IInterface*, boost::forward_traversal_tag, IInterface*>, and cont_iter can be just assigned to it.
Create an abstract IteratorImplementation class:
template<typename T>
class IteratorImplementation
{
public:
virtual ~IteratorImplementation() = 0;
virtual T &operator*() = 0;
virtual const T &operator*() const = 0;
virtual Iterator<T> &operator++() = 0;
virtual Iterator<T> &operator--() = 0;
};
And an Iterator class to wrap around it:
template<typename T>
class Iterator
{
public:
Iterator(IteratorImplementation<T> * = 0);
~Iterator();
T &operator*();
const T &operator*() const;
Iterator<T> &operator++();
Iterator<T> &operator--();
private:
IteratorImplementation<T> *i;
}
Iterator::Iterator(IteratorImplementation<T> *impl) :
i(impl)
{
}
Iterator::~Iterator()
{
delete i;
}
T &Iterator::operator*()
{
if(!impl)
{
// Throw exception if you please.
return;
}
return (*impl)();
}
// etc.
(You can make IteratorImplementation a class "inside" of Iterator to keep things tidy.)
In your Container class, return an instance of Iterator with a custom subclass of IteratorImplementation in the ctor:
class ObjectContainer
{
public:
void insert(Object *o);
// ...
Iterator<Object *> begin();
Iterator<Object *> end();
private:
class CustomIteratorImplementation :
public IteratorImplementation<Object *>
{
public:
// Re-implement stuff here.
}
};
Iterator<Object *> ObjectContainer::begin()
{
CustomIteratorImplementation *impl = new CustomIteratorImplementation(); // Wish we had C++0x's "var" here. ;P
return Iterator<Object *>(impl);
}
Doesn't sound too complicated. You can define the iterator outside. You can also use typedefs. Something like this would fit i think. Note that it would be way cleaner if that MagicIterator would be not a free template, but a member of Item, typedefed in Container maybe. As it's now, there is a cyclic reference in it, which make it necassary to write some ugly workaround code.
namespace detail {
template<typename T, typename U>
struct constify;
template<typename T, typename U>
struct constify<T*, U*> {
typedef T * type;
};
template<typename T, typename U>
struct constify<T*, U const*> {
typedef T const * type;
};
}
template<typename DstType,
typename Container,
typename InputIterator>
struct MagicIterator;
class Container
{
private:
struct Item
{
Object* pObject;
};
std::list<Item> m_items;
public:
// required by every Container for the iterator
typedef std::list<Item> iterator;
typedef std::list<Item> const_iterator;
// convenience declarations
typedef MagicIterator< IInterface*, Container, iterator >
item_iterator;
typedef MagicIterator< IInterface*, Container, const_iterator >
const_item_iterator;
item_iterator Begin();
item_iterator End();
};
template<typename DstType,
typename Container = Container,
typename InputIterator = typename Container::iterator>
struct MagicIterator :
// pick either const T or T, depending on whether it's a const_iterator.
std::iterator<std::input_iterator_tag,
typename detail::constify<
DstType,
typename InputIterator::value_type*>::type> {
typedef std::iterator<std::input_iterator_tag,
typename detail::constify<
DstType,
typename InputIterator::value_type*>::type> base;
MagicIterator():wrapped() { }
explicit MagicIterator(InputIterator const& it):wrapped(it) { }
MagicIterator(MagicIterator const& that):wrapped(that.wrapped) { }
typename base::value_type operator*() {
return (*wrapped).pObject->GetInterface();
}
MagicIterator& operator++() {
++wrapped;
return *this;
}
MagicIterator operator++(int) {
MagicIterator it(*this);
wrapped++;
return it;
}
bool operator==(MagicIterator const& it) const {
return it.wrapped == wrapped;
}
bool operator!=(MagicIterator const& it) const {
return !(*this == it);
}
InputIterator wrapped;
};
// now that the iterator adepter is defined, we can define Begin and End
inline Container::item_iterator Container::Begin() {
return item_iterator(m_items.begin());
}
inline Container::item_iterator Container::End() {
return item_iterator(m_items.end());
}
Now, start using it:
for(MagicIterator<IInterface*> it = c.Begin(); it != c.End(); ++it) {
// ...
}
You can also use a iterator mixin provided by boost, which works like the input version of boost::function_output_iterator. It calls your iterator's operator() which then returns the appropriate value, doing what we do above in our operator* in principle. You find it in random/detail/iterator_mixin.hpp. That would probably result in fewer code. But it also requires to wrack up our neck to ensure the friend-stuff because Item is private and the iterator isn't defined inside Item. Anyway, good luck :)
It really depends on the Container, because the return values of c.Begin() and c.End() are implementation-defined.
If a list of possible Containers is known to MagicIterator, a wrapper class could be used.
template<typename T>
class MagicIterator
{
public:
MagicIterator(std::vector<T>::const_iterator i)
{
vector_const_iterator = i;
}
// Reimplement similarly for more types.
MagicIterator(std::vector<T>::iterator i);
MagicIterator(std::list<T>::const_iterator i);
MagicIterator(std::list<T>::iterator i);
// Reimplement operators here...
private:
std::vector<T>::const_iterator vector_const_iterator;
std::vector<T>::iterator vector_iterator;
std::list<T>::const_iterator list_const_iterator;
std::list<T>::iterator list_iterator;
};
The easy way would be to use a template which accepts Container's type:
// C++0x
template<typename T>
class Iterator :
public T::iterator
{
using T::iterator::iterator;
};
for(Iterator<Container> i = c.begin(); i != c.end(); ++i)
{
// ...
}
More information here.
I see no reason why you can't implement this exactly as you've laid it out... am I missing something?
To clarify, you'll need to put some kind of accessor methods on your Container class. They can be private and you can declare MagicIterator as a friend, if you feel that's the best way to encapsulate it, but I'd expose them directly. These accessor methods would use a normal STL iterator inside Container and perform the conversion to IInterface. Thus the iterating would actually be done with the Container's accessor methods and MagicIterator would just be a kind of proxy object to make it easier. To make it reentrant, you could have the MagicIterator pass in some kind of ID to look up the STL iterator inside Container, or you could actually have it pass in the STL iterator as a void *.
I've now found a solution which is fitter for my original purpose. I still don't like it though :)
The solution involves MagicIterator being templated on IInterface* and being constructed with both a void* to an iterator, the byte size of said iterator, and a table of pointers to functions which perform standard iteration functions on said void* such as increment, decrement, dereference, etc. MagicIterator assumes that it is safe to memcpy the given iterator into an internal buffer, and implements its own members by passing its own buffer as a void* to the supplied functions as if it were the original iterator.
Container then has to implement static iteration functions which cast back a supplied void* to a std::list::iterator. Container::begin() and Container::end() simply construct a std::list::iterator, pass a pointer to it into a MagicIterator along with a table of its iteration functions, and return the MagicIterator.
It's somewhat disgusting, and breaks my original rule regarding "no memcpy()", and makes assumptions about the internals of the iterators in question. But it avoids heap allocation, keeps Collection's internals (including Item) private, renders MagicIterator entirely independent of the collection in question and of IInterface*, and in theory allows MagicIterators to work with any collection (provided its iterators can be safely memcopy()'d).
A visitor may be a simpler (and therefore easier to maintain) solution.