Get class size of object
Simen Kjaeraas
simen.kjaras at gmail.com
Sun Aug 11 12:08:40 PDT 2013
On 2013-08-11, 20:33, JS wrote:
> I think you're missing the point to some degree(I realize there is a
> diff between an object and a type, but I should be able to easily get
> the class size of an object at run time regardless if the object is
> typed as a base class). The code below does this, but at a cost of
> verbosity.
>
> Here is code that exactly demonstrates what I am essentially trying to
> do. The only drawback now is having to mixin the template for each class
> which I would want to automate and it would be nice to wrap the RT and
> CT methods in subclasses without overhead.
It would appear that some information is lost when calling typeid from an
interface. I would have expected this to work:
interface I {
final
size_t size() {
return typeid(this).init.length;
}
}
class A {}
class B : A, I {
int a;
}
void test1() {
I i = new B();
assert(i.size > 0); // Fails.
}
A bit more experimentation shows:
void test2() {
B b = new B();
I i = b;
A a = b;
assert(typeid(a) == typeid(b)); // Passes.
assert(typeid(i) == typeid(b)); // Fails.
assert(typeid(b).init.length > 0); // Passes.
assert(typeid(i).init.length > 0); // Fails.
}
It appears thus that the error is in typeid(interface), which does not
give the actual typeid.
The workaround is as follows:
interface I {
final
size_t size() {
return typeid(cast(Object)this).init.length;
}
}
Is this what you want? Is it good enough? I have no idea, as you're
notoriously bad at describing what you want, but pretty good at
attacking people.
If you're looking for a no-overhead solution, then this might not be
good enough. I'm surprised that a virtual function call is fine,
though.
More information about the Digitalmars-d-learn
mailing list