Re: Difference in compiletime vs compiletime or compiler bug?

2019-12-27 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 27 December 2019 at 18:51:31 UTC, Adam D. Ruppe wrote:
On Friday, 27 December 2019 at 18:49:32 UTC, Sjoerd Nijboer 
wrote:

Should concatenating the list and mixing that in work too?


yeah that'd work too. As long as all the overloads are coming 
from the same source, D allows it.


but if you add something manually in the struct then you have 
two sources again so this rule can bite back.


It's a completely generated body of a struct, so that won't be an 
issue.
It was just convenient to have a static foreach loop and generate 
some functions out of that by invoking a mixin template, which 
will cause the scoping problem.


I'll probably generate the `string[]` using a function, join it 
and then mixin the result to have it all in one scope.


I thought I had a valid usecase for mixin templates. :/
They're quite daunting beasts with these kind of constraints.


Re: Difference in compiletime vs compiletime or compiler bug?

2019-12-27 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 27 December 2019 at 18:34:49 UTC, Adam D. Ruppe wrote:
On Friday, 27 December 2019 at 18:22:10 UTC, Sjoerd Nijboer 
wrote:
When calling the mixin directly instead of through the 
template mixin it breaks with thesame error message.


What exactly did you do here?


I meant to say that that is when it does work.
I shoul've caught this when I proof-read this post.


template mixins take things in two different scopes:

mix!one_string
mix!other_string


creates two separate things that do not overload each other. 
You have to `alias name = xxx` twice in the same scope to merge 
them.


string mixin works differently, it doesn't produce a scope. In 
your case you probably just want to use string mixin and take 
the `mix` item out entirely.


Should concatenating the list and mixing that in work too?

I'll probably remove the mixin template completely, concatenate 
the array of strings and mixin the entire array if that should be 
the proper way for solving this.

Thank you!


Difference in compiletime vs compiletime or compiler bug?

2019-12-27 Thread Sjoerd Nijboer via Digitalmars-d-learn
I've got a snippet of code which I have narrowed down to the 
following:

'import std.stdio;

enum string[] mixins = ["public bool qux(int i, char c)
{
throw new Exception(\"not implemented\");
// Add all arguments to a struct and serialize 
that struct.

};", "
public bool qux(string s)
{
throw new Exception(\"not implemented\");
// Add all arguments to a struct and serialize 
that struct.

};
"];

struct C
{
static foreach (m; mixins)
{
mixin mix!m;
}
}

mixin template mix(string s)
{
mixin(s);
}

void main()
{
import std.traits : ReturnType;

auto c = C();
pragma(msg, c.qux.mangleof); // writes 'v' to the console
pragma(msg, ReturnType!(c.qux));
}'

The exact error this returns is as follows:
'Error: template instance std.traits.ReturnType!(qux) does not 
match template declaration ReturnType(func...)

  with func = (qux)
  must satisfy the following constraint:
   isCallable!func
source/app.d(34,2):while evaluating pragma(msg, 
ReturnType!(qux)

'

As far as I know, this "should" work.
When I delete one of the functions out of the mixin it suddenly 
compiles with a mangled name, but when I place the second 
function in there it won't.
When calling the mixin directly instead of through the template 
mixin it breaks with thesame error message.


I don't know if this an actual compiler bug or if this is me not 
properly understanding D.

I'm using DMD64 D Compiler v2.089.1

Any help is appreciated.


Re: CT filtering of class members

2019-08-11 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Sunday, 11 August 2019 at 16:32:20 UTC, Simen Kjærås wrote:

[...] Something like this:

import std.meta : Filter;
import std.traits : isFunction;
import std.algorithm.searching : canFind;

enum isNonspecialMemberFunction(string name) = 
!ctorAndDtor.canFind(name) &&
   
isFunction!(__traits(getMember, T, name));
enum memberFunctions = Filter!(isNonspecialMemberFunction, 
__traits(derivedMembers, T));


Filter operates on AliasSeqs, not arrays. That's why I restated 
the __traits(derivedMembers, T) part, but this could just as 
easily be done by changing this line:


enum members = [__traits(derivedMembers, T)];

to:

alias members = __traits(derivedMembers, T);

--
  Simen


Works beautiful, thank you very much!



CT filtering of class members

2019-08-11 Thread Sjoerd Nijboer via Digitalmars-d-learn

The following snippet doesn't compile

I am trying to reflect on a class and only do an operation with 
all member functions of a class.
But I can't seem to use a filter to only get the member functions 
out of a type T.


I understand that there are two errors in my snippet.
1) It cannot mixin a `name` because it is a variable from the 
lambda that `filter()` is using.
2) members.filter!(name => !ctorAndDtor.canFind(name)) does not 
filter on symbols defined in ctorAndDtor


How can I fix these problems and return all member functions 
whitout ctor and dtor of a type T?


Code snippet:

void main()
{
GetFunctionMembers!Foo();
}

void GetFunctionMembers(T)()
{
enum members = [__traits(derivedMembers, T)];
pragma(msg, "Functions: " ~ members.stringof);

enum ctorAndDtor = ["this", "__ctor", "__dtor"];
enum memberFunctions = members.filter!(name => 
!ctorAndDtor.canFind(name)

&& mixin("isFunction!(T." ~ name ~ ")"))();

pragma(msg, memberFunctions);
}

class Foo
{
bool myBool;
int k;

this()
{
}

~this()
{
}

void bar(int k)
{
this.k = k;
}

void qux()
{
}
}



Re: generating switch case from compile time sequence of functions

2019-07-15 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Sunday, 14 July 2019 at 19:59:36 UTC, Adam D. Ruppe wrote:

but I think even attempting this is overcomplicating.


static foreach (name; FunctionNames)
{
name ~ " : " ~ name ~ "(); break;";
}


I eventually went with

`switch (mixin(index))
{
static foreach (index, name; FunctionNames)
{
mixin(index) ~ " : " ~ mixin(name) ~ "(); break;";
}
default:
throw new Exception("Out of range.");
}`

I also ditched the idea of an enum for now, but I might add 
something simular in later for logging purposes.

Thank you for your help!



generating switch case from compile time sequence of functions

2019-07-14 Thread Sjoerd Nijboer via Digitalmars-d-learn
I am trying to create a template function with a switch case 
inside it.

The function signature is:
`static void doSwitch(T...)(int i)`

The code it must generate for `doSwitch!(foo, bar)()` is
`{
switch (int)
{
foo:
foo();
return;
bar:
bar();
return;
}
}`

It would be nice if this function would cast `i` to an enum too 
so that I can put down a breakpoint in a debugger and maybe add 
some logging, but that is not strictly neccesary.



The code I have right now is:
`
template switchEnum(FunctionNames...)
{
enum temp = [FunctionNames].join(", ");

enum switchEnum = "{" ~ temp ~ "};";
}

static void doSwitch(FunctionNames...)(int i)
{
auto functionName = cast(switchEnum!FunctionNames) i;

switch (functionName)
{
static foreach (name; FunctionNames)
{
name ~ " : " ~ name ~ "(); break;";
}
}
}
`
But I can't get it to work and am hitting a dead end.
The error I get:
`Error: switchEnum!(foo, bar) is used as a type`



Re: Undescriptive linker error. (bug?)

2019-04-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 5 April 2019 at 22:08:50 UTC, Adam D. Ruppe wrote:

Weird combination of cases that maybe should be illegal.


It errors with the highly descriptive errormessage:

app.obj(app)
 Error 42: Symbol Undefined __D8mymodule3BarFZ3fooMFZCQx3Foo
Error: linker exited with status 1


Undescriptive linker error. (bug?)

2019-04-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

module mymodule;

class Foo{}

Foo Bar()
{
Foo foo();

return foo;
}

int main()
{
auto foo = Bar();

return 0;
}

This code doesn't compile with a linker error that there's a 
missing symbol for `Foo Bar()` on windows.

After all, `Foo foo();` isn't legitimate D.
But why does it return a linker error?
shouldn't it give an error that is more descriptive about a class 
instance being wrong?

I feel like this would be a common thing people try to write.
Especially in templates this would become difficult to narrow 
down.


Re: template with enum parameter doesn't compile

2019-04-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 5 April 2019 at 14:52:05 UTC, lithium iodate wrote:
You are just having a little issue with operator precedence 
there. Your code attempts to get the member `A` from 
`MyClass!MyEnum`, if you add braces around it, it'll work just 
fine `MyClass!(MyEnum.A)`.



That's really funny acutally.
It works. Thank you!



template with enum parameter doesn't compile

2019-04-05 Thread Sjoerd Nijboer via Digitalmars-d-learn
So the following code doesn't compile for some reason, and I 
can't figure out why.


enum MyEnum { A, B, C }

class MyClass(MyEnum myEnum)
{
/*...*/
}

int main()
{
MyClass!MyEnum.A a;
}

The error:  Error: template instance `MyClass!(MyEnum)` does not 
match template declaration `MyClass(MyEnum myEnum)`

pops up, no matter what I do.
I'm quite puzzled actually


Re: public imports

2018-12-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Wednesday, 5 December 2018 at 23:18:49 UTC, H. S. Teoh wrote:
Maybe if you described to us exactly what you want to do, we 
could find a way to do it that doesn't involve language holes 
that are not guaranteed to work?


Honestly I don't know.
I was just messing around.
My initial question was, is this a bug or a feature.
For which I got an answer.



Re: public imports

2018-12-05 Thread Sjoerd Nijboer via Digitalmars-d-learn
On Wednesday, 5 December 2018 at 21:21:12 UTC, Adam D. Ruppe 
wrote:
Looks intended. It doesn't really make sense to have a public 
import inside a function.


I was trying to find a weird corner of the language and maybe do 
something funny with conditional imports.
They don't work in functions, however public imports do work in 
templates, but act as imports that are only visible in that scope.


I was trying to get some form of persistant import outside of the 
function/template scope in the module scope, depending on the 
parameters of the function or template.

I hoped I could find something funny or maybe some usefull trick.
Unfortunately I couldn't :/




public imports

2018-12-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

A small question.
Is it intended behaviour that public imports inside function 
calls fail with the message "Error: found public instead of 
statement", or is it an underdocumented feature?


void foo()
{
public import bar;
}


Re: compile time sequence through dub config or commandline.

2018-12-02 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Sunday, 2 December 2018 at 17:59:56 UTC, Paul Backus wrote:
The normal way to do this would be to make bar a template and 
have the program that uses it pass these parameters to it as 
template arguments.


Why didn't I think of that?
It's just initializing a library, of course!
Thank you for your help and happy coding.



compile time sequence through dub config or commandline.

2018-12-02 Thread Sjoerd Nijboer via Digitalmars-d-learn

I would like to do something like
`
dmd --buildversion=fooCollection{"a", "b", "c"} -run app.d

...

void bar()
{
static foreach(i; fooCollection)
{
...
}
}
`

The idea being that bar can be packed in a library and the 
program that includes this library can decide what parameters 
will be added to foo whitout any runtime overhead and ugly 
looking syntax.


Is something simular possible?
If not, could I achieve thesame result by including a file 
`programsettings.d` with some compile time constants in there 
whitout my library depending on it?


Re: scoped classes and dependency inversion

2018-11-09 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 9 November 2018 at 09:17:27 UTC, Alex wrote:

Is it this what you are looking for?
https://dlang.org/phobos/std_traits.html#Parameters
I've been looking over std.traits all day yesterday, how could 
I've missed that?
I'm so glad there are people in this forum that want to help out 
others like this. :)





Re: scoped classes and dependency inversion

2018-11-09 Thread Sjoerd Nijboer via Digitalmars-d-learn
On Thursday, 8 November 2018 at 21:16:32 UTC, Sjoerd Nijboer 
wrote:
I tried tom make a lazyscoped!T but I'm stuck at creating a 
constructor and determining the arguments from the Type.


Unfortunately I can't find a way in D to get a list of arguments 
at compile time for a given function. Is this at all possible? It 
sounds like an easy case of introspection.


Re: scoped classes and dependency inversion

2018-11-08 Thread Sjoerd Nijboer via Digitalmars-d-learn
On Thursday, 8 November 2018 at 16:31:26 UTC, Neia Neutuladh 
wrote:
I believe what you need to do is pass a factory function into 
the constructor. This is a bit awkward.


Yep, but I want a "nice and descriptive syntax" for it.


Anyway, here's some code to make it work. It's kind of ugly.

---
import std.stdio;
import std.typecons;

void main()
{
auto bar = new Bar!Foo((ref f) { f = scoped!Foo(); });
}

class Bar(TFoo) if(is(TFoo : IFoo))
{
alias SFoo = typeof(scoped!TFoo());
SFoo _foo;
this(void delegate(ref SFoo) dg)
{
dg(_foo);
}
}

class Foo : IFoo
{
void baz(){}
}

interface IFoo
{
void baz();
}
---


I tried to get something more nice looking and I'm stuck on the 
following.
I tried tom make a lazyscoped!T but I'm stuck at creating a 
constructor and determining the arguments from the Type. If I 
could do that I could just forward a lazyscoped!T which would 
have my parameters encapsulated to an object and have that object 
instantiate it at its place.
Maybe not the smartest idea but I think it's a little more 
descriptive than using a factory lambda.


```
import std.typecons : scoped;

void main() {
auto initData = 42;
auto bar = new Bar!Foo(lazyscoped!(Foo)(initData));
}

class Bar(TFoo, TArgs...) if(is(TFoo : IFoo)) {
private typeof(scoped!TFoo())  _foo;

this(lazyscoped!TFoo foo) {
foo.construct(_foo);
}
}

class Foo : IFoo {
int orWhatTypeEver;
this(T)(T myParam) {
orWhatTypeEver = /*cast(int)*/myParam;
}
void baz(){}
}
interface IFoo{ void baz(); }

struct lazyscoped(T) {
import std.typecons : scoped;
	TArgs args; // somehow determine TArgs assumimg there is only 
one __ctor of type T.


this(TArgs args) {
static if(TArgs.length > 0)
this.args = args;
}

void construct(ref typeof(scoped!T()) scoped_t) {
scoped_t = scoped!T(args);
}
}```


Re: scoped classes and dependency inversion

2018-11-08 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Thursday, 8 November 2018 at 12:45:57 UTC, Alex wrote:
Hmm... not sure, if I got your idea... Do you think about 
something like this?



 **snip**


class Bar(TFoo) if(is(TFoo : IFoo))
{
typeof(scoped!TFoo()) _foo;
this()
{
_foo = scoped!TFoo();
}
}


Yes, pretty much.
Except if you want to pass a parameter to TFoo it'll become a 
mess.

And I expecially don't want it to become messy.


scoped classes and dependency inversion

2018-11-08 Thread Sjoerd Nijboer via Digitalmars-d-learn
I'm trying to invert the dependency from the classes `Bar -> Foo` 
to `Foo -> IFoo <- Bar` at compile time.


I do want `Foo's` to be embedded into `Bar`

So silly me tried something like this:
module main;

```import std.stdio;
import std.typecons;

void main()
{
auto bar = new Bar!(scoped!Foo());
}

class Bar (TFoo)
if(is(TFoo == IFoo))
{
scoped!TFoo _foo;
this(scoped!TFoo foo)
{
_foo = foo;
}
}

class Foo : IFoo
{
void baz(){}
}

interface IFoo
{
void baz();
}```

This fails to compile on line 8 since you can't move a scoped!Foo.
So how can I delay the construction of scoped!Foo that it'll end 
up inside Bar?

If there is a more elegant solution I'm also interested.


Re: Keeping a subset of pages allocate via a single call to mmap()

2018-10-13 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Saturday, 13 October 2018 at 18:40:58 UTC, Per Nordlöw wrote:
If a D-program GC-allocates via `new` an array spanning 
multiple pages but after processing only keeps a slice to it 
that fits inside a single `mmape`d page will GC-collection then 
free the other unreferenced pages?


I realize that such a feature in a GC of any language and type 
must rely on the OS memory manager being able to free parts of 
a previously allocated set of continuously positioned pages.


Does this depend on whether the used page is the first, last or 
a page in the middle of the set of pages allocated in one call 
to mmap.


I don't believe the GC frees half of allocated memory if there 
are no references to the unreferenced point.

It would break c style strings I think.


Re: Alligned gc allocation of struct

2018-10-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 5 October 2018 at 14:55:04 UTC, Dennis wrote:

On Friday, 5 October 2018 at 10:03:35 UTC, Kagamin wrote:

GC allocations are 16 bytes aligned.


Is that an implementation detail or well-defined behavior?


The GC_Allocator doesn't support alignedAllocate from the 
IAllocate interface, which is kinda unfortunate.

So I'm a little worried that this might change in the future.


Re: Alligned gc allocation of struct

2018-10-05 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Friday, 5 October 2018 at 10:03:35 UTC, Kagamin wrote:

GC allocations are 16 bytes aligned.


That's perfect. Thank you!


Alligned gc allocation of struct

2018-10-05 Thread Sjoerd Nijboer via Digitalmars-d-learn
I've got a `struct Foo{ubyte16 field1, field2 fieldn;}` for 
which I would like a heap allocation `Foo* foo = new Foo();` But 
the fields itsself must be 16 bytes aligned for SIMD instructions.

Is there a neat way to do this in D?
As far as I can tell the GC_allocator doesn't do aligned 
allocations by default.


Re: inline ASM function calling conventions.

2018-09-30 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Sunday, 30 September 2018 at 12:32:08 UTC, kinke wrote:

1) `asm {}` is supported by DMD and LDC, but not by GDC.


Good to know.
Guess I will be targeting DMD and LDC then.

4) For x86_64, there are 2 (completely different) ABIs, Win64 
and the System V one. Specs can be found online.


In your case:

void Foo(MyStrunct* first_arg, MyStrunct* second_arg)
{
asm { naked; }
version (D_InlineAsm_X86)
{
// first_arg is on the stack, at [ESP+4]
// second_arg is in EAX
}
else version (D_InlineAsm_X86_64)
{
version (Win64)
{
// first_arg is in RDX
// second_arg is in RCX
}
else
{
// first_arg is in RSI
// second_arg is in RDI
}
}
}


So in X86 asm, if I want to pas two parameters to a function I 
can have one in a register, but not two. The second will go via 
the stack. But on X86_64 it won't?

Guess I'll just have to live with that.
Thank you!


Re: inline ASM function calling conventions.

2018-09-30 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Sunday, 30 September 2018 at 12:07:53 UTC, Basile B. wrote:

On Sunday, 30 September 2018 at 11:53:17 UTC, Basile B. wrote:


Hello, i think this should be here 
(https://dlang.org/spec/abi.html) because myself i never 
remember them correctly without playing a bit with a 
disassembler.

After playing a bit:


Thank you for the link, very informative!
I'm spitting it through right now.



Without all the save/restore BS:

module runnable;

import std.stdio;

alias write4Int = writeln!(int,int,int,int);

struct MyStruct{int i;}

extern(D) void foo(ref MyStruct s1, ref MyStruct s2, ref 
MyStruct s3, ref MyStruct s4)

{
asm
{
naked;
mov RCX, MyStruct.i.offsetof[RCX];
mov RDX, MyStruct.i.offsetof[RDX];
mov RSI, MyStruct.i.offsetof[RSI];
mov RDI, MyStruct.i.offsetof[RDI];
callwrite4Int;
ret;
}
}

void main()
{
MyStruct s1 = MyStruct(1);
MyStruct s2 = MyStruct(2);
MyStruct s3 = MyStruct(3);
MyStruct s4 = MyStruct(4);
foo(s1, s2, s3, s4);
}


In X86_64 it works beautiful!
But in X86 it will pass them via the stack, and I'm trying to get 
rid of that.





inline ASM function calling conventions.

2018-09-30 Thread Sjoerd Nijboer via Digitalmars-d-learn

I'm kinda puzzled.

I'm having trouble getting started with inline asm in D.
Suppowse I have the following:

void Foo(MyStrunct* first_arg, MyStrunct* second_arg)
{
asm
{
naked;
version(X86)
{
/* Do something with the content of I and J. */
}
version(X86_64)
{
/* Do something with the content of I and J. *?
}
}
}

void Bar()
{
MyStrunct heapStructA, heapStructB;

// do some initialization.

Foo(heapStructA, heapStructB);
}

Suppose I would like to pass first_arg and second_arg by register 
to `Foo`, what calling convention should I use? I'm having 
trouble identifying the correct calling convention I should be 
using for X86 and X86_64 in D.


I've tried a couple using https://godbolt.org/ and DMD parameters 
'-g -m32', but I can't seem to find any that will pass by 
register. Is there one? Will it also work for LDC and GDC?


Re: Locking data

2018-05-22 Thread Sjoerd Nijboer via Digitalmars-d-learn
On Tuesday, 22 May 2018 at 22:17:05 UTC, IntegratedDimensions 
wrote:

On Tuesday, 22 May 2018 at 22:10:52 UTC, Alex wrote:
On Tuesday, 22 May 2018 at 21:45:07 UTC, IntegratedDimensions 
wrote:

an idea to lock data by removing the reference:

class A
{
   Lockable!Data data;
}

The idea is that when the data is going to be used, the user 
locks the data. The trick here is that data is a pointer to 
the data and the pointer is set to null when locked so no 
other data can use it(they see a null reference). To unlock, 
the data is reassigned:


auto d = data.lock(); // A.data is now null deals with sync 
issues

//use d
d = data.unlock(d); // restores A.data (A.data = d;) and sets 
d to null so any future reference is an error(could produce 
bugs but should mostly be access violations)



Anyone else trying to use data will see that it is null while 
it is locked.


This basically pushes the standard locking mechanisms in to 
the Lockable!data(first come first serve) and code that has 
not captured the data see's it simply as null.


Anyone use know if there exists an idiom like this and what 
it is called? Maybe some idiomatic code that is efficient?



Ideally I'd want to be able to treat the Lockable!Data as 
Data. Right now I have to classes(or pointers to structs) and 
few weird hacks. I think what I'll have to end up doing is 
having a Locked!Data structure that is returned instead or 
use an UFCS. The idea being to attach the lock and unlock 
methods.


Are you aware of NullableRef?
https://dlang.org/library/std/typecons/nullable_ref.html



Yes.


Does it fit somehow?


Not really. It could be used to wrap the data when used as a 
struct but it offers none of the locking features which is the 
ultimate goal.


The idea is simply that one can lock the data to get exclusive 
access. Normally standard locking tricks are used but in this 
case the idea is to do all that behind the scenes. Locking the 
data makes all other accessors see null data(and crash or 
properly test). This is a first come first serve or single 
access type of pattern but sort of removes the data from prying 
eyes while it is being used.


how about something like

 import core.atomic;
 class Lockable!Data
 {
private __gshared Lockable!Data data;
 }

 struct Locked!Lockable!Data
 {
private TailShared!Lockable!Data lockedData;
private Lockable!Data lockableData;

this(Lockable!Data lockableData)
{
this.lockableData = lockableData;
while( (lockedData= atomicLoad(lockableData)) !is null)
if(cas(lockedData, lockedData, null))
break;
}

~this()
{
atomicStore(lockedData, lockableData );
}

alias lockedData.data this;
 }

With something like this you should be able to do RAII like 
semantics on your data.
You share a Lockable!Data which you want use, and then you can 
access it if you instantiate a Locked!Lockable!Data struct with 
it.

FYI, my atomics isn't all that great so don't expect this to work.



Re: Creating a template mixin for explicit casts.

2018-05-17 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Thursday, 17 May 2018 at 20:38:13 UTC, Sjoerd Nijboer wrote:

But then how do you put this into a mixin template so I can ...
mixin castingRules(typeof(this) T);


I guess I can refine my question to "How do you let a mixin 
template detect the template name it is instantiated with and 
return its type whitout the template arguments.





Re: Creating a template mixin for explicit casts.

2018-05-17 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Thursday, 17 May 2018 at 16:27:48 UTC, Paul Backus wrote:

On Thursday, 17 May 2018 at 15:25:37 UTC, Sjoerd Nijboer wrote:
I want to make a template mixin that is able to cast one of 
these generic structs to the other explicitly. I have a bunch 
of these structs and therefore I thought it would make sense 
to do it by template mixin. I just don't know what language or 
library features I need to use and how to apply them.


It sounds like you want to overload opCast:

https://dlang.org/spec/operatoroverloading.html#cast


Something like:
`
Foo!T opCast(U)(Foo!U old)
if (isImplicitlyConvertible!(T, U))
{
return Foo!T(old.t);
}

Foo!T opCast(UTemplate, U)(UTemplate!U old)
if (isImplicitlyConvertible!(T, U) && isNumerical!U)
{
return Foo!T(old.t);
}

`
But then how do you put this into a mixin template so I can write 
something like

`
struct Foo(T)
if(isNumerical(T))
{
mixin castingRules(typeof(this) T);
}
`


Creating a template mixin for explicit casts.

2018-05-17 Thread Sjoerd Nijboer via Digitalmars-d-learn

Given the following code
`struct Foo(T)
if(isNumeric!T)
{
T t;
.. other code
}

struct Bar(T)
if(isNumeric!T)
{
T t;
.. other code
}

Foo!float foo_float;

Foo!double foo_double;

Bar!float bar_float;
`

I want to make a template mixin that is able to cast one of these 
generic structs to the other explicitly. I have a bunch of these 
structs and therefore I thought it would make sense to do it by 
template mixin. I just don't know what language or library 
features I need to use and how to apply them.


`
fooDouble = cast (Foo!double) foo_float;		// case [1] if 
possible, done by

// an implicit cast. 
Else by
//explicit.

fooFloat = cast (Foo!float) foo_double; // case [2]

barFloat = cast (Bar!float) foo_float;  // case [3]
`

How would I do this in D?


Re: Is using function() in templates possible at all?

2018-04-11 Thread Sjoerd Nijboer via Digitalmars-d-learn

On Wednesday, 11 April 2018 at 21:29:27 UTC, Alex wrote:

I would say, alias template parameter is your friend.
https://dlang.org/spec/template.html#TemplateAliasParameter

class SortedList(T, alias comparer)


It works, thank you!
But just to be shure, there's no way to have this more strongly 
typed in D so I can enforce that `comparer`is a funciton or 
delegate with a specific defenition?
Right now i'm relying on the template to error on some different 
place which might not give such a readable error message to the 
user.


Is using function() in templates possible at all?

2018-04-11 Thread Sjoerd Nijboer via Digitalmars-d-learn

I am trying to do a binary insert into my sorted array.
To sort classes and structs I would like to give a delegate `(t) 
=> t.myValue` to sort on that value whitout having to implement 
an interface or specifically declare opCmp for every class I want 
to have sorted.
After all, I might want one group of objects of a given class 
sorted in one way and another group of objects sorted on another 
way depending on the usecase.
In C# this is done by passing on a lambda in for instance a LinQ 
expression to sort such list after insertion, and is also usefull 
in other circumstances.


But is it possible in D to do something simular but then pass on 
this Function() during compile time?


something like
`
void main() { SortedList!(Vector3, (v) => v.y) list; }

struct Vector3 { float x, y, z; }

class SortedList(T, int function(T) comparer)
{
T[] array;

int foo(T t)
{
for(int i = 0; i < array.lenght; i++)
{
if(comparer(this.otherT) <=  comparer(t))
{
//do stuff
array[i] = t;
}
}
}
}
`