Re: Is it possible to avoid call to destructor for structs?
Here's a simple solution. Just make Bar a pointer and free it before it can be destructed! import std.stdio; struct Bar { ~this() { writeln("~bar"); } } struct Foo { Bar *bar; this(int why_the_fuck_dont_structs_have_default_constructors) { bar = new Bar; } ~this() { writeln("~foo"); import core.memory; GC.free(bar); } }
Re: Is it possible to avoid call to destructor for structs?
Here's a simple solution. Just make Bar a pointer and free it before it can be destructed! import std.stdio; struct Bar { ~this() { writeln("~bar"); } } struct Foo { Bar *bar; this(int why_the_fuck_dont_structs_have_default_constructors) { bar = new Bar; } ~this() { writeln("~foo"); import core.memory; GC.free(bar); } }
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 23:24:58 UTC, user1234 wrote: On Wednesday, 27 September 2017 at 21:01:36 UTC, Jesse Phillips wrote: On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller wrote: My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask. My answer is that & is a defined operation on all addressable memory. Unlike other operators which don't exist until you "overload" them. Yes but the dereference operator can be overloaded. The reasoning doesn't stand, unless that's recognized as an inconsistency. Except that no it actually doesn't. The Unary operator * doesn't overload the dereferencing of a pointer, take the following code: class Test { Test opUnary(string s)() if (s == "*") { writeln("Overloaded operator called"); return this; } } void testFunc() { Test test = new Test(); Test* test_ptr = &test; writeln("== *test =="); Test other = *test; writeln("== *test_ptr =="); other = *test_ptr; writeln("== end =="); } This outputs: == *test == Overloaded operator called == *test_ptr == == end == Notice how dereferencing the pointer did not call the overloaded function, because a pointer to Test is not the same type as a Test.
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 21:01:36 UTC, Jesse Phillips wrote: On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller wrote: My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask. My answer is that & is a defined operation on all addressable memory. Unlike other operators which don't exist until you "overload" them. Yes but the dereference operator can be overloaded. The reasoning doesn't stand, unless that's recognized as an inconsistency.
Re: What does ! mean?
On Wednesday, 27 September 2017 at 14:34:06 UTC, Eugene Wissner wrote: On Wednesday, 27 September 2017 at 14:23:01 UTC, Ky-Anh Huynh wrote: See also the following chapter in Ali's book: http://ddili.org/ders/d.en/templates.html This chapter is what hooked me with D. Naming that chapter as "Templates for Human Beings" won't be an exaggeration.
Re: What does ! mean?
On Wednesday, 27 September 2017 at 17:58:27 UTC, Ali Çehreli wrote: On 09/27/2017 08:33 AM, Ky-Anh Huynh wrote: > [...] Wissner wrote: > [...] The fact that such an important operator is explained so late in the book is due to the book's strong desire to have a linear flow. [...] ustad, guess you can still write the new ed. :-)
Re: What does ! mean?
On 09/27/2017 03:06 PM, Mengu wrote: ustad, guess you can still write the new ed. :-) Since you're still around, one of these days... :) Ali
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 21:18:50 UTC, nkm1 wrote: On Wednesday, 27 September 2017 at 20:24:24 UTC, DreadKyller wrote: The attitude of "some people use this feature incorrectly, so let's ban it's use entirely" is honestly ridiculous to me, but oh well, that's apparently the modern philosophy. Not even modern, see Java :) ("I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++." - James Gosling) Oh don't get me wrong, I'm not saying that not allowing operator overloading is new, and Java doesn't allow any, like at all, compared to D just not allowing a handful. And I wasn't referring to operator overloading specifically, I was talking in general about how it's become more common with modern languages to try being overly safe, in attempt to prevent users from making mistakes. It's not that it's particularly problematic, but it does tend to make some more recent languages far more verbose and tedious to type. This philosophy has existed since very early on, it's just become more common in the last decade or so. I just disagree with the concept, I just happen to feel that had the effort that was put into the philosophy and design of making things safer had been put into educating and developing better tools and resources then the need for such restrictions would be less essential. In general I feel D has a good balance of this, there are restrictions that I dislike, but can work around them because or the benefits of the language, despite what I see as several flaws in the design personally, it's still currently my favorite language. Also off-topic slightly, but am I the only one with massive latency on this site? It took like almost 2 minutes from me hitting reply before this page showed up, and my last few posts took like a minute to post, and all other sites I've been to don't have that problem, is that a problem with the site or am I the only one with this issue?
Re: Allocating byte aligned array
On Wednesday, 27 September 2017 at 21:44:48 UTC, Ali Çehreli wrote: On 09/27/2017 02:39 PM, timvol wrote: [...] void main() { auto mem = new ubyte[1024+15]; auto ptr = cast(ubyte*)(cast(ulong)(mem.ptr + 15) & ~0x0FUL); auto arr = ptr[0..1024]; } Ali Works perfect. Thank you!
Re: Allocating byte aligned array
On 09/27/2017 02:39 PM, timvol wrote: Hi guys, how can I allocate an (e.g. 16) byte aligned array? In C I can do the following: void *mem = malloc(1024+15); void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F; memset_16aligned(ptr, 0, 1024); free(mem); I think in D it looks similar to this: auto mem = new ubyte[1024+15]; auto ptr = (mem.ptr + 15) & ~ (...???...) 0x0F; How to fill ...???... ? Without a cast, the compiler tells me that I the types are incompatible (ubyte* and int). What's the correct syntax here? PS: I don't want to use the experimental branch that provides alignedAllocate(). void main() { auto mem = new ubyte[1024+15]; auto ptr = cast(ubyte*)(cast(ulong)(mem.ptr + 15) & ~0x0FUL); auto arr = ptr[0..1024]; } Ali
Allocating byte aligned array
Hi guys, how can I allocate an (e.g. 16) byte aligned array? In C I can do the following: void *mem = malloc(1024+15); void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F; memset_16aligned(ptr, 0, 1024); free(mem); I think in D it looks similar to this: auto mem = new ubyte[1024+15]; auto ptr = (mem.ptr + 15) & ~ (...???...) 0x0F; How to fill ...???... ? Without a cast, the compiler tells me that I the types are incompatible (ubyte* and int). What's the correct syntax here? PS: I don't want to use the experimental branch that provides alignedAllocate().
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 20:24:24 UTC, DreadKyller wrote: The attitude of "some people use this feature incorrectly, so let's ban it's use entirely" is honestly ridiculous to me, but oh well, that's apparently the modern philosophy. Not even modern, see Java :) ("I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++." - James Gosling)
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 21:01:36 UTC, Jesse Phillips wrote: For example, if you store your Matrix in a custom container it could try to store pointer rather than the struct itself, if & is overloaded the generic implementation would be broken because it would no longer be a pointer to Matrix but to the inner element. Whereas generic code which utilizes addition or append can assume the type appropriately defined the behavior to semantically match the desired use, generic code would be broken if the type changed & to do something different from what the language defines it to do. Alright, that makes sense, that's some valid reasoning, I can accept that.
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller wrote: My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask. My answer is that & is a defined operation on all addressable memory. Unlike other operators which don't exist until you "overload" them. For example, if you store your Matrix in a custom container it could try to store pointer rather than the struct itself, if & is overloaded the generic implementation would be broken because it would no longer be a pointer to Matrix but to the inner element. Whereas generic code which utilizes addition or append can assume the type appropriately defined the behavior to semantically match the desired use, generic code would be broken if the type changed & to do something different from what the language defines it to do.
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 19:55:07 UTC, nkm1 wrote: On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller wrote: Been using D for a couple years now, however one problem I've had, more so recently since I've been dealing a lot with OpenGL is related to pointers. I have a matrix object to aid with the matrix math required for working with 3D transforms. However OpenGL (I'm using DerelictGL3 bindings) requires pointers to the data. I am currently doing the following: Matrix!float ortho(float l, float r, float b, float t, float f, float n = -1) { Matrix!float oMat = identity(); // Get default Identity Matrix oMat[0,0] = 2 / (r - l); oMat[1,1] = 2 / (t - b); oMat[2,2] = -2 / (f - n); oMat[3] = [-(r+l)/(r-l), -(t+b)/(t-b), -(f+n)/(f-n), 1]; return oMat; } And then to use with OpenGL (passing as uniform into shader): glUniformMatrix4fv(transform_uniform, 1, GL_FALSE, matrix.addr ); where addr is a property that returns the address of the first item in the Matrix's internal data. I know I can also use &matrix[0][0] My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask. & is not overloadable, presumably because some people were annoyed by abuse of operator overloading in C++. The reason is to improve readability (of other people's code). Just rename matrix.addr to matrix.ptr... like in arrays: https://dlang.org/spec/arrays.html#array-properties That would be clearer (opinion), since the reader of your code can assume that matrix.ptr does the same thing with your matrix as array.ptr does with arrays. OTOH, overloading &matrix to do something different from built in &matrix seems like a pointless obfuscation to me. I mean to an extent I agree, but I moved from using GLfloat arrays for matrix's to a Matrix object to aid in Matrix math like multiplication, so I have to go through my code and in many places change it to using matrix.ptr, considering that I have to do this for every object in a scene multiple times for the translation, scale, projection and etc matrix's it's more tedious, and I'm the only one working on the code and I comment and document my code a lot. If one thing annoys m e about language design, it's when peoples actions dictate the decisions of the language, it shouldn't be the responsibility of the language to limit users in order to prevent bad habits or practices, it should be the responsibility of education to do so. The attitude of "some people use this feature incorrectly, so let's ban it's use entirely" is honestly ridiculous to me, but oh well, that's apparently the modern philosophy.
Re: Is it possible to specify the address returned by the address of operator?
On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller wrote: Been using D for a couple years now, however one problem I've had, more so recently since I've been dealing a lot with OpenGL is related to pointers. I have a matrix object to aid with the matrix math required for working with 3D transforms. However OpenGL (I'm using DerelictGL3 bindings) requires pointers to the data. I am currently doing the following: Matrix!float ortho(float l, float r, float b, float t, float f, float n = -1) { Matrix!float oMat = identity(); // Get default Identity Matrix oMat[0,0] = 2 / (r - l); oMat[1,1] = 2 / (t - b); oMat[2,2] = -2 / (f - n); oMat[3] = [-(r+l)/(r-l), -(t+b)/(t-b), -(f+n)/(f-n), 1]; return oMat; } And then to use with OpenGL (passing as uniform into shader): glUniformMatrix4fv(transform_uniform, 1, GL_FALSE, matrix.addr ); where addr is a property that returns the address of the first item in the Matrix's internal data. I know I can also use &matrix[0][0] My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask. & is not overloadable, presumably because some people were annoyed by abuse of operator overloading in C++. The reason is to improve readability (of other people's code). Just rename matrix.addr to matrix.ptr... like in arrays: https://dlang.org/spec/arrays.html#array-properties That would be clearer (opinion), since the reader of your code can assume that matrix.ptr does the same thing with your matrix as array.ptr does with arrays. OTOH, overloading &matrix to do something different from built in &matrix seems like a pointless obfuscation to me.
Inter-module symbol resolution error of template type-parameter when using mixins
At https://github.com/nordlow/phobos-next/blob/03b4736fdd65ef84c6fc583eddee4196629cea81/src/variant_arrays.d I've implemented a lightweight-polymorphic array container I call `VariantArrays(Types...)` indexed by a corresponding polymorphic index I call `VariantIndex(Types...)`. It uses `.mangleof` together with mixins to automatically infer the definition (including its name) of each array store for each element type in `Types`. The element types are passed in the template parameter `Types` to the two templated structs mentioned above. Everything works except for when I try to instantiate `VariantArrays` from within a module other than `variant_arrays.d`. For instance, if I try to use it another module containing unittest { struct S { int x; } import variant_arrays : VariantArrays; VariantArrays!S a; } I get the error variant_arrays.d-mixin-130(130,1): Error: undefined identifier `S` foo.d(5,5): Error: template instance variant_arrays.VariantArrays!(S) error instantiating In other words, the symbol `S` cannot be resolved in the scope of `VariantArrays` eventhough it's feed as a template parameter. Is there a way around this problem? Here follows the definition of variant_arrays.d (excluding unittests): /** Polymorphic index into an element in `VariantArrays`. */ private struct VariantIndex(Types...) { import std.meta : staticIndexOf; private: alias Kind = ubyte; // kind code alias Size = size_t; // size type import bit_traits : bitsNeeded; /// Number of bits needed to represent kind. enum kindBits = bitsNeeded!(Types.length); /// Get number kind of kind type `SomeKind`. enum nrOfKind(SomeKind) = staticIndexOf!(SomeKind, Types); // TODO cast to ubyte if Types.length is <= 256 /// Is `true` iff an index to a `SomeKind`-kind can be stored. enum canReferTo(SomeKind) = nrOfKind!SomeKind >= 0; /// Construct. this(Kind kind, Size index) // TODO can ctor inferred by bitfields? { _kindNr = kind; _index = index; } import std.bitmanip : bitfields; mixin(bitfields!(Size, "_index", 8*Size.sizeof - kindBits, Kind, "_kindNr", kindBits)); } /** Stores set of variants. Enables lightweight storage of polymorphic objects. Each element is indexed by a corresponding `VariantIndex`. */ private struct VariantArrays(Types...) { alias Index = VariantIndex!Types; import basic_copyable_array : CopyableArray; /// Returns: array type (as a string) of `Type`. private static immutable(string) arrayTypeString(Type)() { return `CopyableArray!(` ~ Type.stringof ~ `)`; } /// Returns: array instance (as a strinng) storing `Type`. private static immutable(string) arrayInstanceString(Type)() { return `_values` ~ Type.mangleof; } /** Insert `value` at back. */ pragma(inline) // DMD cannot inline Index insertBack(SomeKind)(SomeKind value) // TODO add array type overload if (Index.canReferTo!SomeKind) { mixin(`alias arrayInstance = ` ~ arrayInstanceString!SomeKind ~ `;`); const currentIndex = arrayInstance.length; arrayInstance.insertBack(value); return Index(Index.nrOfKind!SomeKind, currentIndex); } alias put = insertBack; // polymorphic `OutputRange` support /// Get reference to element of type `SomeKind` at `index`. scope ref inout(SomeKind) at(SomeKind)(in size_t index) inout return if (Index.canReferTo!SomeKind) { mixin(`return ` ~ arrayInstanceString!SomeKind ~ `[index];`); } /// Peek at element of type `SomeKind` at `index`. scope inout(SomeKind)* peek(SomeKind)(in Index index) inout return @system if (Index.canReferTo!SomeKind) { if (Index.nrOfKind!SomeKind == index._kindNr) { return &at!SomeKind(index._index); } else { return null; } } private: // TODO this fails: mixin({ string s = ""; foreach (Type; Types) { s ~= arrayTypeString!Type ~ ` ` ~ arrayInstanceString!Type ~ `;`; } return s; }()); }
Re: What does ! mean?
On 09/27/2017 08:33 AM, Ky-Anh Huynh wrote: > On Wednesday, 27 September 2017 at 14:34:06 UTC, Eugene Wissner wrote: >> >> See also the following chapter in Ali's book: >> http://ddili.org/ders/d.en/templates.html > > Thanks a lot. I will keep reading :) The fact that such an important operator is explained so late in the book is due to the book's strong desire to have a linear flow. Although binary ! appears before the templates chapter as to!int, format!"%s", etc., I decided to get to templates only after going through everything that could be templatized. (For example, even interfaces can be templates.) I don't claim this is the best choice but I'm happy that some people said that they found the linear flow useful. (I know that others would find it boring. :) ) If I were to write the book again, one other thing that I would explain earlier would be UFCS, and I would use much more of it in the examples. (UFCS was added to the language after I wrote most of the book.) Ali
Is it possible to specify the address returned by the address of operator?
Been using D for a couple years now, however one problem I've had, more so recently since I've been dealing a lot with OpenGL is related to pointers. I have a matrix object to aid with the matrix math required for working with 3D transforms. However OpenGL (I'm using DerelictGL3 bindings) requires pointers to the data. I am currently doing the following: Matrix!float ortho(float l, float r, float b, float t, float f, float n = -1) { Matrix!float oMat = identity(); // Get default Identity Matrix oMat[0,0] = 2 / (r - l); oMat[1,1] = 2 / (t - b); oMat[2,2] = -2 / (f - n); oMat[3] = [-(r+l)/(r-l), -(t+b)/(t-b), -(f+n)/(f-n), 1]; return oMat; } And then to use with OpenGL (passing as uniform into shader): glUniformMatrix4fv(transform_uniform, 1, GL_FALSE, matrix.addr ); where addr is a property that returns the address of the first item in the Matrix's internal data. I know I can also use &matrix[0][0] My question is about overloading, several operators can be overloaded in D, one of the ones that can't apparently is the address of operator (&object). My question is have I simply missed it or does it actually not exist, and if it's not overloadable, is there any reason why this was decided? Because there's been numerous times that it'd be useful to me, just recently with how much I use the operator because of OpenGL I decided to ask.
Re: Can I skip sub directories with file.dirEntries() ?
On Wednesday, 27 September 2017 at 10:05:34 UTC, Nicholas Wilson wrote: I'd just use dirEntries with SpanMode.shallow in combination with filter either in a loop or a recursive function like below. void foo(string path = "path") { foreach(e; dirEntries(path,SpanMode.shallow).filter!(myCritreia(paramters))) { if (e. isDir) foo(e.name); // recurse // do other stuff } } you will loop over all subdirs of "path" that satisfy `myCritreia`. Thank you Nicolas. It's a good idea. PS: With Linux find command, the thing can be done easily with `-prune` option: ``` find . -iname node_modules -prune ``` Without `-prune` option, there are a lot of unnecessary sub directories...
Re: What does ! mean?
On Wednesday, 27 September 2017 at 14:23:01 UTC, Ky-Anh Huynh wrote: Can you please explain and give any link where I can learn more about these things? Thanks a lot. http://nomad.so/2013/07/templates-in-d-explained/
Re: What does ! mean?
On Wednesday, 27 September 2017 at 14:34:06 UTC, Eugene Wissner wrote: See also the following chapter in Ali's book: http://ddili.org/ders/d.en/templates.html Thanks a lot. I will keep reading :)
Re: What does ! mean?
On Wednesday, 27 September 2017 at 14:23:01 UTC, Ky-Anh Huynh wrote: Hi, I am from Ruby world where I can have `!` (or `?`) in method names: `!` indicates that a method would modify its object (`foo.upcase!` means `foo = foo.upcase`). ( I don't know if there is any official Ruby documentation on this convention though. ) In D I see `!` quite a lot. I have read the first 50 chapters in Ali's book but nowhere I see a note on `!`. It's about the compile thing, isn't it? E.g, ``` foo = formattedRead!"%s"(value); ``` But I also see `!` for some map/filter invocations. It's quite confusing me. Can you please explain and give any link where I can learn more about these things? Thanks a lot. See also the following chapter in Ali's book: http://ddili.org/ders/d.en/templates.html
Re: What does ! mean?
There are two types of arguments in D. The runtime one (which you are well aware of) and the compile time one. A compile time argument is a constant passed in during construction of a symbol. But here is the thing, it isn't just limited to functions, you can have it on classes as well. --- class Foo(bool b) { bool get() { return b; } } void main() { Foo!true v = new Foo!true; assert(v.get); } --- Same logic going on. --- bool get(bool b)() { return b; } void main() { assert(get!true == true); } --- It can do more than a simple boolean being passed in, but that is the gist. Templates are wonderful (also read the spec!).
What does ! mean?
Hi, I am from Ruby world where I can have `!` (or `?`) in method names: `!` indicates that a method would modify its object (`foo.upcase!` means `foo = foo.upcase`). ( I don't know if there is any official Ruby documentation on this convention though. ) In D I see `!` quite a lot. I have read the first 50 chapters in Ali's book but nowhere I see a note on `!`. It's about the compile thing, isn't it? E.g, ``` foo = formattedRead!"%s"(value); ``` But I also see `!` for some map/filter invocations. It's quite confusing me. Can you please explain and give any link where I can learn more about these things? Thanks a lot.
Sectioned variables?
GCC supports a `__attribute((section("...")))` for variables to put them in specific sections in the final assembly. Is there any way this can be achieved in D? Does GDC support this?
Re: Can I skip sub directories with file.dirEntries() ?
On Wednesday, 27 September 2017 at 09:00:55 UTC, Ky-Anh Huynh wrote: Hi, Can I have a `break` option when using `dirEntries()` (similar to `break` in a loop)? I want to study sub-directories but if any sub-directory matches my criteria I don't to look further into their subdirectories ``` A/ -> matches criteria, stop here, go to next directory (B) B/ -> doesn't match criteria, will look at its sub-directories (BX, BY,...) BX BY ``` Thanks a lot I'd just use dirEntries with SpanMode.shallow in combination with filter either in a loop or a recursive function like below. void foo(string path = "path") { foreach(e; dirEntries(path,SpanMode.shallow).filter!(myCritreia(paramters))) { if (e. isDir) foo(e.name); // recurse // do other stuff } } you will loop over all subdirs of "path" that satisfy `myCritreia`.
Can I skip sub directories with file.dirEntries() ?
Hi, Can I have a `break` option when using `dirEntries()` (similar to `break` in a loop)? I want to study sub-directories but if any sub-directory matches my criteria I don't to look further into their subdirectories ``` A/ -> matches criteria, stop here, go to next directory (B) B/ -> doesn't match criteria, will look at its sub-directories (BX, BY,...) BX BY ``` Thanks a lot