Click to See Complete Forum and Search --> : objects as template parameters
kedaman
Oct 29th, 2001, 08:02 AM
struct asdf{int z;};
template <asdf* y>
class c{static const int l;};
template <asdf* y>
const int c<y>::l=y->z;
I wonder how the compiler deals with this? It sure compiles but the templatized class c has to instantiate at compile time, how on earth is it suppose to dereference the asdf pointer :confused:
CornedBee
Oct 29th, 2001, 10:18 AM
did you try to use this construct? I mean, which address do you supply as template parameter? It must be a constant (like 0xa00000), am I right?
kedaman
Oct 29th, 2001, 01:12 PM
struct asdf{int z;asdf(int pz):z(pz){};} x(4);
template <asdf* y>
struct c{static const int l;};
template <asdf* y>
const int c<y>::l=y->z;
int main(){
cout << c<&x>::l << endl;
x.z=5;
cout << c<&x>::l << endl;
return 0;
};
It seems like it's done at compile time, at least changing it at runtime won't affect the datatype. I am truly amazed by this :)
BTW can anyone check it out with assembler listings? I don't want to rely that it executes a contructor and why not a whole bunch of functions at compile time if it actually doesnt :eek:
CornedBee
Oct 29th, 2001, 01:30 PM
My best guess:
the address of a variable is known at compile time. Therefor it can be used to create a real struct out of your template. The created code looks like this:
struct asdf{
int z;
asdf(int pz)
:z(pz)
{};
} x(4);
struct _@3479AD32h_@c { // or whatever temporary name where the template parameter is coded inside
static const int l;
};
// this is copied here, so it doesn't need to change later
const int _@3479AD32h_@c::y = (asdf*)(0x3479AD32)->z;
int main(){
cout << _@3479AD32h_@c::l << endl;
x.z=5; // this has no effect because _@3479AD32h_@c::l is a copy of x.z, not a reference
cout << _@3479AD32h_@c::l << endl;
return 0;
};
(&x = 0x3479AD32)
Is my assumption true?
kedaman
Oct 29th, 2001, 02:05 PM
Okay :) That gives new life in partial evaluation with templates which didn't work too well in MSVC
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.