On Friday, 18 June 2021 at 09:05:38 UTC, Mike Brown wrote:
>Hi all,
I would like to convert a D string to an int - im doing this in a compile time function as well. conv throws an error due to it using TypeInfo?
How would I do this?
Kind regards,
Mike
BetterC has some CTFE-related bugs atm that might be the problem here.
You could if you need betterC use libc at runtime,
extern (C) void main() {
import core.stdc.stdlib : atoi;
import core.stdc.stdio : printf;
const n = atoi("123"); // not enum
printf("%d\n", n);
}
or if you're more concerned about limiting the GC, you can use @nogc annotations for that while still having more of the language at CTFE and elsewhere:
void main() @nogc nothrow {
import core.stdc.stdio : printf;
import std.conv : to;
enum n = to!int("123"); // not const
printf("%d\n", n);
}
If n
were const in that last example:
exmaple.d(5): Error: `@nogc` function `D main` cannot call non-@nogc function `std.conv.to!int.to!string.to`
example.d(5): Error: function `std.conv.to!int.to!string.to` is not `nothrow`
example.d(1): Error: `nothrow` function `D main` may throw