digitalmars.D.learn - Why is this pure function taking a string literal not CTFE-executable?
- Simon (56/56) Jun 01 2019 Hi Guys!
Hi Guys! In my programm, I have a custom String-type that I want to initialize some variables of at compile time by casting a string literal to said custom String type. I thought I could achieve this straight forwardly, but after trying a bit, I could not find a (simple) working solution. I made this minimal example to show where the easy solution all fall flat: struct My_String{ long size; char* data; } My_String make_my_string(string s){ My_String my_string; my_string.data = cast(char*) s.ptr; my_string.size = s.length; return my_string; } struct Dummy{ My_String s = make_my_string("hello!"); } void main(){ Dummy dummy; } Which produces the compilation error "cannot use non-constant CTFE pointer in an initializer My_String(6L, &"hello!"[0])". I do not understand this error message. What is the non-constant CTFE pointer here. The "data"-member? If so, why does this compile: struct My_String{ long size; char* data; } struct Dummy{ My_String s = My_String("hello!".length, cast(char*) "hello!".ptr); } void main(){ Dummy dummy; } Why does the error message show an opcall to My_String with filled out members ("6L, &"hello!"[0]"), although the code only ever default-constructs a My_string variable? I am confused. And why on earth does this work: struct My_String{ long size; char* data; } My_String make_my_string(string s){ My_String my_string; my_string.data = cast(char*) s.ptr; my_string.size = s.length; return my_string; } void main(){ My_String s = make_my_string("hello!"); } Please help, I have no idea whats going on here.
Jun 01 2019