Boost logo

Boost :

From: Luis Pedro Coelho (deepblack9_at_[hidden])
Date: 2002-02-15 23:38:52


Em Quarta, 13 de Fevereiro de 2002 22:56, escreveste:
> Let's go back to your original reasoning:
> > value doesn't know where A is, but
> > it knows where it is
> > ...
>
> 'value', being in any case something inside an instance of class A, only
> knows where it is at run-time, not at compile-time.
> There is really no way to get to the final address of the actual 'value' at
> compile-time.
>
> Once again: the actual address of the any data inside any C++ object isn't
> know at compile-time not at link-time, only at runtime.
> There is no way out of this inherent limitation, you need one way or
> another runtime support to bind the accesors to the actual value.

Yes, value only knows where it is at runtime. What I wanted to say is that
given that knowledge it should be possible to work out where A is, at
runtime. That's why I wrote:

A* a = reinterpret_cast<A*>(reinterpret_cast<unsigned char*>(this) + offset);

The big problem is in calculating offset. This is a compile time constant. If
one could get some way of knowing it there would be no need for properties to
carry around a pointer to their parents. They could work it out from there
own addresses at run time from a compile-time calculated offset. This is
basically the reverse operation from the one done by the compiler to find out
the address of an subobject given the address of the parent.

I could not get the following to compile:

struct A {
        X<A,&A::value> value;
};

The problem being that A::value is unkown at the point where it is placed.
The second problem is how to declare X.

template <typename T, ?????>
struct X {
};

I did get the following to work where the address of s is correctly worked
out:

#include <iostream>
 
using namespace std;
 
template <typename T,
    int T::* const Ptr_To_Member>
struct X {
        void* f() {
                T* t = reinterpret_cast<T*>(this);
                int* i = &(t->*Ptr_To_Member);
                long offset = reinterpret_cast<unsigned char*>(t) -
reinterpret_cast<unsigned char*>(i);
                return reinterpret_cast<unsigned char*>(this) + offset;
        }
};
 
struct A {
        int a;
        int s;
        X<A,&A::s> value;
};
 
int main()
{
        A a;
        cout << "&a.s = " << (void*)&a.s << endl;
        cout << "a.value() = " << a.value.f();
        cout << endl;
}

-- 
Luis Pedro Coelho.

Check out my game of Hearts, a card game, for KDE at:
http://hearts.sourceforge.net/


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk