问题
What is the minimal set of nested typedefs that should be defined in a custom STL class meeting the Sequence concept? The custom sequence should be compatible with:
- std::back_insert_iterator
- BOOST_FOREACH
- Boost range concept.
回答1:
The C++ Standard says all containers must have the following typedefs (C++03 23.1/Table 65):
value_type
reference
const_reference
iterator
const_iterator
difference_type
size_type
Reversible containers must have the following typedefs (C++03 23.1/Table 66):
reverse_iterator
const_reverse_iterator
回答2:
I came up with this program to find the mininal set of nested typedefs:
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/sort.hpp>
struct Foo
{
typedef std::vector<int> Vec;
typedef Vec::const_reference const_reference;
typedef Vec::iterator iterator;
typedef Vec::const_iterator const_iterator;
iterator begin() {return vec.begin();}
iterator end() {return vec.end();}
const_iterator begin() const {return vec.begin();}
const_iterator end() const {return vec.end();}
void push_back(const int& n) {vec.push_back(n);}
Vec vec;
};
int main()
{
Foo f;
std::back_insert_iterator<Foo> it(f);
*it = 2; ++it; *it = 1; ++it;
boost::sort(f);
BOOST_FOREACH(int x, f)
{
std::cout << x << " ";
}
}
As you can see, at least const_reference
, iterator
, and const_iterator
are needed.
I should mention that I compiled this with gcc 4.4.3 and boost 1.43.
来源:https://stackoverflow.com/questions/4823761/minimal-set-of-nested-typedefs-for-a-custom-stl-sequence