views:

292

answers:

4

Does anyone know why the following generates an error on VC9?

class Elem;
class ElemVec : public vector<Elem>
{
    public:
        void foo();
};

void ElemVec::foo()
{
    BOOST_FOREACH(Elem& elem, *this)
    {
        // Do something with elem
    }
    return;
}

The error I get is:

error C2355: 'this' : can only be referenced inside non-static member functions

The only (hack) solution I have right now which compiles without error is:

void ElemVec::foo()
{
    ElemVec* This = this;
    BOOST_FOREACH(Elem& elem, *This)
    {
        // Do something with elem
    }
    return;
}
A: 

I had never seen that error. I guess it comes from the implementation of BOOST_FOREACH macro.

May i ask why you're creating a class based on vector<...> and not having a vector member variable ?

EDIT Following this thread, i found out that this actually is a visual studio bug. The solution you have found seems to be the simplest.

Benoît
In this case, I am extending the vector<Elem> with some extra functionality that I need.
Ashwin
Generally a bad idea - write free functions instead of using inheritance.
anon
Inheriting from vector is generally bad because of it's non virtual destructor. As long as you are aware of this, extending should be ok..
Indeera
Benoit: I am aware of that Boost mailing list thread. What I'm surprised is that it hasn't been fixed since VC7/8 days!
Ashwin
@indeera unfortunately not only have you got to be aware of it, the users of your code have too
anon
@Neil, I agree with you. Perhaps I didn't convey properly, I meant to say generally to cover wide range of scenarios, where as if the author knows the implications of his decisions, he could use this in a specific application.
Indeera
+3  A: 

You shouldn't inherit from STL containers. These are not polymorphic classes and it's the reason BOOST_FORACH can't handle your derived class.

Try to use aggregation instead.

Assaf Lavie
What is BOOST_FOREACH doing that prevents it from being applied on such a class?
Ashwin
A: 

Hmm, all compiled succesfully on my msvc (2005) compiller.

Maybe you have some error, but fixed or avoided it when was created your example.

bb
Thanks, as "dirkgently" pointed out, it turned out to be a Boost issue. The error no longer occurs with the latest Boost v1.38.
Ashwin
A: 

Which compiler/Boost version are you using? I can compile the following without any problem (VS2005/Boost 1.38):

#include <boost/foreach.hpp>
using namespace std;
struct xxx : std::vector<int>
{
    void test()
    {
        BOOST_FOREACH(int x, *this)
        {
        }
    }
}; 

int main(void) {
    xxx x;
    x.test();
    return 0;
}

Search the Boost bugbase if you want more details.

dirkgently
Thanks for pointing that out. I'm on Boost 1.35, I will upgrade to 1.38 and get back to you.
Ashwin
The error is gone with Boost 1.38. Thanks a lot! :-)
Ashwin