Can I assign a member data pointer to a derived type?

This is probably best shown with example code. The following fails to compile with g++:

struct Base {
};

struct Derived : public Base {
};

struct Container {
    Derived data_;
};

int main(void) {
    Base Container::*ptr = &Container::data_;
}

I get the following error: invalid conversion from 'Derived Container::*' to Base Container::*'. Is this not allowed by the language? Is this a compiler bug? Am I using the wrong syntax?

Please help!

Some background as to why I'm trying to do this: I have several member data pieces that I want to use primarily as their derived types, but I want to be able to populate them through some common code. Data will be coming in an arbitrary order and have a string label that I would use to select the appropriate member data to populate. I was planning on creating a std::map to assign data to each member through a common interface. I'd like to avoid have a giant if else construct to find the right member data.

13
задан preynold 16 May 2011 в 13:17
поделиться