boost foreach with protected inheritance of container
I'm getting a compile time error with the following code. The error pops up on the use of BOOST_FOREACH on line 23:
17 class MyVec: protected std::vector<int>
18 {
19 public:
20 void add(int i) { this->push_back(i); }
21 void print()
22 {
23 BOOST_FOREACH(int i, *this)
24 std::cout << i;
25 std::cout << std::endl;
26 }
27 };
However, if I change protected
to public
at line 17, it compiles & runs as expected. Moreover, I can iterate just fine by using the standard boiler-plate code with iterators.
Why is this happening?? Any help would be appreciated! :-)
EDIT: Does this mean I cannot use BOOST_FOREACH without publicly exposing begin() & end() ? EDTI2: Actually, the const_iterator & iterator types also need to be exposed.
When you inherit with protected
specifier, the public members of the base class become protected in the derived class.
BOOST::FOR_EACH
implementation likely tries to call begin()
and end()
, but can't.
Adding two using declarations in the definition of MyVec
solves it for me (I'm using gcc):
using std::vector<int>::begin;
using std::vector<int>::end;
If it helps understanding the error, consider this:
class MyVec;
void my_foreach(const MyVec&);
class MyVec: protected std::vector<int> {
void print() {
my_foreach(*this);
}
};
void my_foreach(const MyVec& v)
{
v.begin(); // error std::vector<int> is not an accessible base
}
I'm not familiar with the exact implementation of this macro, but I believe that's the crux of the error you're getting. If you're interested, dive in the source code for it and maybe read this nice article for an explanation.
链接地址: http://www.djcxy.com/p/47358.html上一篇: 在std :: for中使用boost.lambda
下一篇: 用容器的保护继承来推动foreach