static map as a type function
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.com
Thu Sep 24 16:33:37 UTC 2020
On 9/24/20 11:59 AM, Stefan Koch wrote:
> On Thursday, 24 September 2020 at 15:57:03 UTC, Stefan Koch wrote:
>> On Thursday, 24 September 2020 at 15:54:55 UTC, Adam D. Ruppe wrote:
>>> On Thursday, 24 September 2020 at 14:36:45 UTC, Stefan Koch wrote:
>>>> Let me show you the code that does only typeid.name
>>>
>>> What if TypeInfo was templated instead of magically generated? So the
>>> compiler doesn't need to do all this stuff.
>>
>> You still have to instantiate all those templates and do it correctly.
>> Which means the compiler needs some way of exposing all the
>> information via the templates system.
>>
>> Which essentially requires the same code.
>
> Oh and typeinfo has to be generated eagerly!
> Whereas the current way it works with ctfe is lazy.
> Which means as long as nothing else requires typeinfo, using it at CTFE
> does not require you to generate it.
> So code that only uses type info at ctfe does compile with -betterC.
Actually it works to generate typeinfo objects lazily, on demand. I was
quite surprised about how nicely that works as I was working on
https://github.com/dlang/druntime/pull/3174/files.
I sketched something here:
https://run.dlang.io/is/PjRo9w
The code compiles and evaluates correctly during compilation. The URL
shortener seems to have problems so I'll also paste the code below:
// Base class for CT and RT type information.
immutable abstract class NewTypeInfo {
size_t tsize();
}
// Implementation for given type T.
immutable class NewTypeInfoImpl(T) : NewTypeInfo {
override size_t tsize() {
return T.sizeof;
}
}
// Use __typeid!T to get a singleton object associated with type T.
@property immutable(NewTypeInfo) __typeid(T)() {
static immutable singleton = new NewTypeInfoImpl!T;
return singleton;
}
auto static_map_tf(alias F)(immutable NewTypeInfo[] types...)
{
typeof(F(types[0]))[] result;
result.length = types.length;
foreach(i, t; types)
{
result[i] = F(t);
}
return result;
}
static assert(static_map_tf!(t => t.tsize)(__typeid!int,
__typeid!ushort) == [4, 2]);
void main() {}
More information about the Digitalmars-d
mailing list