Where are the template members?
Timon Gehr
timon.gehr at gmx.ch
Wed Dec 5 01:09:48 PST 2012
On 12/05/2012 09:51 AM, Simen Kjaeraas wrote:
> On 2012-39-05 09:12, Gor Gyolchanyan <gor.f.gyolchanyan at gmail.com> wrote:
>
>> Consider this piece of code:
>>
>> struct Test
>> {
>> template member(Type)
>> {
>> Type member;
>> }
>> }
>>
>> unittest
>> {
>> Test test;
>> test.member!int = 0;
>> test.member!long = 0;
>> test.member!short = 0;
>> import std.stdio; writeln(test.sizeof);
>> assert(test.sizeof == int.sizeof + long.sizeof + short.sizeof); // fails
>> assert(test.sizeof == 1); // succeeds
>> }
>>
>> I don't get why the structure's size remains unchanged even after
>> instantiating 3 members inside it.
>> How can I get the real size of the structure, including all its members
>> (template or not)?
>
> You have. Its real size is 1, and the template instantiations are not
> member
> fields.
>
> A template (not a templated function [actually, sorta, but that's a
> different
> discussion]) is basically static - if you try instead Test.member!int, you
> will see that this works perfectly.
>
> What we see here is another example of the confusion that can be caused by
> static names being accessible through an instance:
>
> struct Foo {
> static int n;
> }
>
> Foo f;
>
> f.n = 4;
>
> --
> Simen
The confusion is caused by implicitly marking fields static during
template instantiation instead of failing compilation.
More information about the Digitalmars-d
mailing list