"Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Tue Apr 9 00:02:02 UTC 2024


On 09/04/2024 11:42 AM, Liam McGillivray wrote:
> On Monday, 8 April 2024 at 08:12:22 UTC, Richard (Rikki) Andrew 
> Cattermole wrote:
>>>> ```d
>>>> template Foo(Args) {
>>>>     enum Foo = () {
>>>>         return Args.init;
>>>>     }();
>>>> }
>>>> ```
>>>>
>>>> Something like that should work instead.
>>>
>>> I'm sorry, but I can't comprehend any of your example. What would be 
>>> fed into `Args`? I don't understand how this works, or how I would 
>>> use it for what I want.
>>
>> You would replace it with whatever template parameters you want 
>> (including nothing). It's there as a place holder.
>>
>> Same for the return on the closure.
>>
>> But the main thing to understand is that the closure that gives the 
>> enum a value, that'll be CTFE only, no runtime target.
> 
> Are you saying that this is a way to guarantee that the code is 
> compile-time only?

More or less.

> I still understand very little of this code. I'm not experienced in D 
> metaprogramming; just the function I posted above was a major 
> achievement for me. I don't understand how I would use the code you gave 
> in place of the function I have written and posted above.

Let's break it down.

The expression that initializes the ``func`` variable, this is a 
closure. The ``a`` and ``b`` are function parameter names (types do not 
need to be provided).

```d
alias FuncType = int function(int, int);

FuncType func = (a, b) {
	return a + b;
};

int value = func(1, 2);
```

The alias is used to give a name to the function pointer type.

Next, let's combine the function pointer storage variable with the 
result with the call.

```d
int value = (a, b) {
	return a + b;
}(1, 2);
```

We can swap the type ``int`` for the ``enum`` keyword, this produces a 
compile time constant that is an ``int`` that has the value 3.

```d
enum Value = (a, b) {
	return a + b;
}(1, 2);
```

This alone should be a CTFE only function.

But if we want template parameters, we'd need to wrap it with the template.

```d
template Value(int a, int b) {
	enum Value = () {
		return a + b;
	}();
}

int value = Value!(1, 2);
```

Does that help?


More information about the Digitalmars-d-learn mailing list