A
Alessandro [AkiRoss] Re
Hello,
I'm in a situation where an object (class User), contained in another
object (class Container), need to get a reference to its container.
Here's a working code that does what I mean:
struct User {
template <typename C> User(C &cont) { /* ... */ }
};
struct Container {
User u, v, z;
Container(): u(*this), v(*this), z(*this) {}
};
My problem: I'd like to remove the X(*this), in some way.
In other words: when an User object is instantiated within the
Container class, it should get in some way a reference/pointer to the
Container instance.
I thought about using a method which return the address of the
Container instance, and passing it as template parameter, like this:
template <typename C, C &(C::*instance)()>
struct User {
User() {
C &c = ???->*instance();
}
};
struct Container {
Container &self() { return *this; }
User<Container, &Container::self> u;
};
But, of course, this doesn't work, because calling the instance()
pointer-to-method required an associated instance to work with, and
it's exactly what I'm trying to get
Why I'm doing this? Because in the Container class (or any subclass),
they may be a lot of User instances, and it's rather unpractical to
initialize them one by one in the constructor list.
How can I do this?
Thanks,
~Ale
I'm in a situation where an object (class User), contained in another
object (class Container), need to get a reference to its container.
Here's a working code that does what I mean:
struct User {
template <typename C> User(C &cont) { /* ... */ }
};
struct Container {
User u, v, z;
Container(): u(*this), v(*this), z(*this) {}
};
My problem: I'd like to remove the X(*this), in some way.
In other words: when an User object is instantiated within the
Container class, it should get in some way a reference/pointer to the
Container instance.
I thought about using a method which return the address of the
Container instance, and passing it as template parameter, like this:
template <typename C, C &(C::*instance)()>
struct User {
User() {
C &c = ???->*instance();
}
};
struct Container {
Container &self() { return *this; }
User<Container, &Container::self> u;
};
But, of course, this doesn't work, because calling the instance()
pointer-to-method required an associated instance to work with, and
it's exactly what I'm trying to get
Why I'm doing this? Because in the Container class (or any subclass),
they may be a lot of User instances, and it's rather unpractical to
initialize them one by one in the constructor list.
How can I do this?
Thanks,
~Ale