How to use ".stringof" to get the value of a variable and not the name of the variable (identifier) itself?
Imperatorn
johan_forsberg_86 at hotmail.com
Tue Oct 10 05:32:52 UTC 2023
On Monday, 9 October 2023 at 22:49:11 UTC, Salih Dincer wrote:
> On Monday, 9 October 2023 at 16:33:32 UTC, rempas wrote:
>> I'm trying to create a series of function. There will be ten
>> of them, and they will be called `function_0`, `function_1`,
>> etc. However, in my example, "stringof" returns the character
>> "i" itself and turns that into a string instead of getting its
>> actual value (number).
>>
>> Any ideas how I can achieve what I'm trying to achieve?
>
> Great masters generally warn to stay away from stringof. Please
> do not use it as much as possible. The following code snippet
> will be useful to you:
>
> ```d
> alias CN = __traits(allMembers, CardinalNumbers);
>
> static foreach(i; CN)
> {
> mixin(create_fn!(i[1]));
> }
>
> enum create_fn(char num) = `
> auto function_`~ num ~`()
> => "Hello from function `~ num ~`!";
> `;
>
> enum CardinalNumbers
> {
> n0, n1, n2, n3, n4, n5, n6, n7, n8, n9
> }
>
> void main()
> {
> assert(function_9() == "Hello from function 9!");
> }
> ```
>
> SDB at 79
If count < 10 then why not just
```d
import std;
static foreach(c; "0123456789")
{
mixin(create_fn!(c));
}
enum create_fn(char num) = `
auto function_`~ num ~`()
=> "Hello from function `~ num ~`!";
`;
void main()
{
assert(function_9() == "Hello from function 9!");
}
```
More information about the Digitalmars-d-learn
mailing list