But why aren't they non-static members? If they were non-static members the structure's size would still be compile-time, computed by the sum of sizes of all template instances. the .sizeof would work perfectly well.
This would be an incredibly useful feature. Among other use cases this would allow having a fully type-safe and very fast Variant type:

struct Variant
{
public:
TypeInfo type() @property
{
return _type;
}
ref Type_ as(Type_)() @property
{
if(typeid(Type_) != _type)
throw new Exception("The requested static type doesn't match the available dynamic type.");
return _value!Type_;
}
private:
TypeInfo _type;

union
{
template _value(Type_)
{
Type_ _value;
}
}
}

Is there any good reason why this feature wouldn't be a good idea?


On Wed, Dec 5, 2012 at 12:51 PM, Simen Kjaeraas <simen.kjaras@gmail.com> wrote:
On 2012-39-05 09:12, Gor Gyolchanyan <gor.f.gyolchanyan@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



--
Bye,
Gor Gyolchanyan.