Insert if doesn't exist without double lookup.

2014-03-15 Thread Agustin

Hello!, i would like to know if this is possible.

auto asValue ?= (map["Key"] == new Value);

Instead of doing:

if (("Key" in map) is null)
   map["Key"] = new Value
auto asValue = map["Key"];


Re: BinaryHeap

2013-11-27 Thread Agustin

On Thursday, 7 November 2013 at 14:31:27 UTC, Agustin wrote:

On Thursday, 7 November 2013 at 12:29:44 UTC, bearophile wrote:

Agustin:


no property 'popFront' for type 'BinaryHeap!(uint[])'


Try to use front and removeFront (I don't know why there is 
removeFront instead of popFront).


Bye,
bearophile


I had to implement a custom IterableBinaryHeap implementation.

http://pastebin.com/GeVAeCch

IterableBinaryHeap!(Array!uint, "a < b") heap;
heap.insert(0);
heap.insert(3);
heap.insert(2);
heap.insert(1);
foreach(item; heap)
writeln(item);


The above code was working until i upgrade to DMD32 D Compiler 
v2.064.


Now i got:
  "Error: cannot uniquely infer foreach argument types"

Help!


Re: Function is not implemented.

2013-11-26 Thread Agustin

On Tuesday, 26 November 2013 at 17:50:12 UTC, Ali Çehreli wrote:

On 11/26/2013 09:32 AM, Agustin wrote:

I'm trying to move from Java to D, and i have some like this:

interface A
{
  public bool isCancelled();
  public void setCancelled(bool value);
}

class B
{
  public bool isCancelled();
  protected void setCancelled(bool value);
}

But when i do

class C : B, A
{}

I get

Engine/Main.d(6): Error: class Main.C interface function 'bool
isCancelled()' is not implemented
Engine/Main.d(6): Error: class Main.C interface function 'void
setCancelled(bool value)' is not implemented


You have to provide the implementations of the interface 
functions either in B or C. I think you actually tested with B 
implementations though:


class B
{
public bool isCancelled()
{
// implemented
return false;
}

protected void setCancelled(bool value)
{
// implemented
}
}

Still the same error...

Unless you want to implement the functions on C as well, then C 
should not inherit from A. A is already inherited by B:


class C : B// <-- no A
{}

Ali


Oh i forgot to add the implementation here, but its there, what i 
want to do is with an interface be able to change "protected" to 
"public", this is possible using Java but i don't know if 
possible using D.



class C : B, A -> setCancelled() is changed from protected to 
public

{
}




Function is not implemented.

2013-11-26 Thread Agustin

I'm trying to move from Java to D, and i have some like this:

interface A
{
  public bool isCancelled();
  public void setCancelled(bool value);
}

class B
{
  public bool isCancelled();
  protected void setCancelled(bool value);
}

But when i do

class C : B, A
{}

I get

Engine/Main.d(6): Error: class Main.C interface function 'bool 
isCancelled()' is not implemented
Engine/Main.d(6): Error: class Main.C interface function 'void 
setCancelled(bool value)' is not implemented


Re: interface and class inheritance

2013-11-14 Thread Agustin

On Thursday, 14 November 2013 at 21:20:57 UTC, Oleg B wrote:

[code]
import std.stdio;

interface A { void funcA(); }
class B { final void funcA() { writeln( "B.funcA()" ); } }

class C: B, A { }

void main()
{
auto c = new C;
c.funcA();
}
[code/]

$ dmd -run interface.d
interface.d(6): Error: class interface.C interface function 
'void funcA()' is not implemented


if swap A and B
[code]
class C: A, B { }
[code/]

$ dmd -run interface.d
interface.d(6): Error: class interface.C base type must be 
interface, not interface.B


how to workaround this without change in class B and interface 
A?


Try

interface A {
  final void funcA();
}
class B {
  final void funcA() { writeln( "B.funcA()" ); }
}

class C: B, A { }



Re: interface and class inheritance

2013-11-14 Thread Agustin

On Thursday, 14 November 2013 at 21:42:38 UTC, Agustin wrote:

On Thursday, 14 November 2013 at 21:20:57 UTC, Oleg B wrote:

[code]
import std.stdio;

interface A { void funcA(); }
class B { final void funcA() { writeln( "B.funcA()" ); } }

class C: B, A { }

void main()
{
   auto c = new C;
   c.funcA();
}
[code/]

$ dmd -run interface.d
interface.d(6): Error: class interface.C interface function 
'void funcA()' is not implemented


if swap A and B
[code]
class C: A, B { }
[code/]

$ dmd -run interface.d
interface.d(6): Error: class interface.C base type must be 
interface, not interface.B


how to workaround this without change in class B and interface 
A?


Try

interface A {
  final void funcA();
}
class B {
  final void funcA() { writeln( "B.funcA()" ); }
}

class C: B, A { }


Oh sorry i mean

interface A {
  void funcA();
}

class B : A {
  final void funcA() { writeln( "B.funcA()" ); }
}

class C : B {
}


Cannot cast char[] to string.

2013-11-14 Thread Agustin
I'm trying to use http://dlang.org/phobos/std_net_curl.html and 
when i compile the same example i get:


cannot implicitly convert expression 
(get(cast(const(char)[])address, AutoProtocol())) of type char[] 
to string


string address = "http://dlang.org";;
string _data = get(address);


Re: function XXXX conflict with YYYY

2013-11-14 Thread Agustin
Thanks, i updated to v2.064.2 and everything works just fine. I 
had this issue long time ago and it was annoying to have multiple 
function with different names.


function XXXX conflict with YYYY

2013-11-14 Thread Agustin

final uint registerEvent(T, J)(IPlugin, void delegate(J))
{
 
}

final uint registerEvent(IPlugin, EventHandler, EventInfo, ulong)
{
 
}

There seems to be a problem when having two function with same 
name but different parameters. Only happend when one of the 
function use templates. Is that a compiler limitation?


Unexpected OPTLINK Termination at EIP=000000000

2013-11-07 Thread Agustin
I'm getting "Unexpected OPTLINK Termination at EIP = 0 
and assembly register values" when compiling the follow code. I'm 
doing something wrong?


class MyClass
{
  void opCall()
  {
  }
}

public void main(string[] arguments)
{
MyClass clazz = new MyClass();
TaskPool pool = new TaskPool();

pool.put(std.parallelism.task(&clazz.opCall));
}


Re: BinaryHeap

2013-11-07 Thread Agustin

On Thursday, 7 November 2013 at 12:29:44 UTC, bearophile wrote:

Agustin:


no property 'popFront' for type 'BinaryHeap!(uint[])'


Try to use front and removeFront (I don't know why there is 
removeFront instead of popFront).


Bye,
bearophile


I had to implement a custom IterableBinaryHeap implementation.

http://pastebin.com/GeVAeCch

IterableBinaryHeap!(Array!uint, "a < b") heap;
heap.insert(0);
heap.insert(3);
heap.insert(2);
heap.insert(1);
foreach(item; heap)
writeln(item);



Re: BinaryHeap

2013-11-07 Thread Agustin

On Thursday, 7 November 2013 at 12:45:11 UTC, Agustin wrote:

On Thursday, 7 November 2013 at 12:29:44 UTC, bearophile wrote:

Agustin:


no property 'popFront' for type 'BinaryHeap!(uint[])'


Try to use front and removeFront (I don't know why there is 
removeFront instead of popFront).


Bye,
bearophile


Saddly i had to do this

auto clone = _heap.dup;

while (!clone.empty())
{
auto item = clone.front();
// ... Do something with item
clone.removeFront();
}

Iterate directly over a binary heap will be better perfomance 
wise than doing that because i had to clone the heap to be able 
to iterate over without removing items from the original heap.


By looking at the source, having "private @property ref Store 
_store()" public will help a lot.


Re: BinaryHeap

2013-11-07 Thread Agustin

On Thursday, 7 November 2013 at 12:29:44 UTC, bearophile wrote:

Agustin:


no property 'popFront' for type 'BinaryHeap!(uint[])'


Try to use front and removeFront (I don't know why there is 
removeFront instead of popFront).


Bye,
bearophile


Saddly i had to do this

auto clone = _heap.dup;

while (!clone.empty())
{
auto item = clone.front();
// ... Do something with item
clone.removeFront();
}

Iterate directly over a binary heap will be better perfomance 
wise than doing that because i had to clone the heap to be able 
to iterate over without removing items from the original heap.


Re: BinaryHeap

2013-11-07 Thread Agustin

On Thursday, 7 November 2013 at 12:14:22 UTC, Agustin wrote:

On Thursday, 7 November 2013 at 09:00:11 UTC, bearophile wrote:

Agustin:

I'm trying to use BinaryHeap and i found out that i cannot 
use foreach(). My question is, there is any other way to do 
it?, can i iterate a BinaryHeap?


Please show the code :-)

Perhaps you need to look at the head, pop the head item, look 
at the head, etc.


Bye,
bearophile


BinaryHeap!(uint[]) heap;
foreach(type; heap)
{
 
}

no property 'popFront' for type 'BinaryHeap!(uint[])'


It seems that i need to have a pointer to the underlying array.

uint[] intArray;
BinaryHeap!(uint[]) heap;
heap.acquire(intArray);
foreach(int; intArray)
{
 
}


Re: BinaryHeap

2013-11-07 Thread Agustin

On Thursday, 7 November 2013 at 09:00:11 UTC, bearophile wrote:

Agustin:

I'm trying to use BinaryHeap and i found out that i cannot use 
foreach(). My question is, there is any other way to do it?, 
can i iterate a BinaryHeap?


Please show the code :-)

Perhaps you need to look at the head, pop the head item, look 
at the head, etc.


Bye,
bearophile


BinaryHeap!(uint[]) heap;
foreach(type; heap)
{
 
}

no property 'popFront' for type 'BinaryHeap!(uint[])'


BinaryHeap

2013-11-06 Thread Agustin
I'm trying to use BinaryHeap and i found out that i cannot use 
foreach(). My question is, there is any other way to do it?, can 
i iterate a BinaryHeap?


Re: Weird thing related to stdio.

2013-10-23 Thread Agustin

On Thursday, 24 October 2013 at 02:20:39 UTC, Agustin wrote:

On Thursday, 24 October 2013 at 02:18:29 UTC, Agustin wrote:
My code contains zero console write call, and when i add 
std.stdio in a specific module i get some text about the 
classes i defined using mixin.


If i add std.stdio here: http://pastebin.com/3kRQEvpu i get 
"3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream50org.ghrum.protocol.message.stream.MessageStream70org.ghrum.protocol.message.stream.MessageStream"


Classes: http://pastebin.com/CCRp872R
Functions: http://pastebin.com/K2dtSAtL


Forgot to mention that the message is printed on the console 
when i execute

"pPlayerMoveCodec.write(pMessageStream, pPlayerMoveMessage);"


Also if i add std.stdio, io fails for some weird reason :/


Re: Weird thing related to stdio.

2013-10-23 Thread Agustin

On Thursday, 24 October 2013 at 02:18:29 UTC, Agustin wrote:
My code contains zero console write call, and when i add 
std.stdio in a specific module i get some text about the 
classes i defined using mixin.


If i add std.stdio here: http://pastebin.com/3kRQEvpu i get 
"3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream50org.ghrum.protocol.message.stream.MessageStream70org.ghrum.protocol.message.stream.MessageStream"


Classes: http://pastebin.com/CCRp872R
Functions: http://pastebin.com/K2dtSAtL


Forgot to mention that the message is printed on the console when 
i execute

"pPlayerMoveCodec.write(pMessageStream, pPlayerMoveMessage);"


Weird thing related to stdio.

2013-10-23 Thread Agustin
My code contains zero console write call, and when i add 
std.stdio in a specific module i get some text about the classes 
i defined using mixin.


If i add std.stdio here: http://pastebin.com/3kRQEvpu i get 
"3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream3org.ghrum.protocol.message.stream.MessageStream50org.ghrum.protocol.message.stream.MessageStream70org.ghrum.protocol.message.stream.MessageStream"


Classes: http://pastebin.com/CCRp872R
Functions: http://pastebin.com/K2dtSAtL


Re: Error: unsupported char 0x03

2013-10-22 Thread Agustin

On Tuesday, 22 October 2013 at 15:16:17 UTC, bearophile wrote:

John Colvin:


do you perhaps want to!string(id) ???


Or:

id.text

Bye,
bearophile



I like id.text better than to!string, thanks


Re: Error: unsupported char 0x03

2013-10-22 Thread Agustin

On Tuesday, 22 October 2013 at 15:05:16 UTC, Adam D. Ruppe wrote:

On Tuesday, 22 October 2013 at 15:01:20 UTC, Agustin wrote:
   = "public immutable(int) getId() const { \n" ~ id ~ "; 
\n}";


You'll probably want to convert id to a string there

import std.conv;

 "public immutable(int) getId() const { \n" ~ to!string(id) ~ ";

and also put in return for that function:
 "public immutable(int) getId() const { \n return " ~ 
to!string(id) ~ ";



and it should compile. What was happening before is string ~ 
int implicitly converts the int to a char, and cast(char)(3) 
isn't a printable character, and isn't allowed in D source code.


Works great, thanks! :)


Error: unsupported char 0x03

2013-10-22 Thread Agustin

Trying to use mixin, i get an unsupported char error.

protected template GenMessageGetId(uint id) {
immutable string GenMessageGetId
= "public immutable(int) getId() const { \n" ~ id ~ "; 
\n}";

}

public mixin template Packet(uint id, T...) {
...

private static string buildPacket() {
 ...

 return GenMessageGetId!(id);
}

mixin (buildPacket());
}

class MyPacket : Message {
mixin Packet!(3, ...); -> Error: unsupported char 0x03
}

GenMessageGetId is generating "unsupported char 0x03".


Re: Error: unsupported char 0x03

2013-10-22 Thread Agustin

On Tuesday, 22 October 2013 at 15:01:20 UTC, Agustin wrote:

Trying to use mixin, i get an unsupported char error.

protected template GenMessageGetId(uint id) {
immutable string GenMessageGetId
= "public immutable(int) getId() const { \n" ~ id ~ "; 
\n}";

}

public mixin template Packet(uint id, T...) {
...

private static string buildPacket() {
 ...

 return GenMessageGetId!(id);
}

mixin (buildPacket());
}

class MyPacket : Message {
mixin Packet!(3, ...); -> Error: unsupported char 0x03
}

GenMessageGetId is generating "unsupported char 0x03".


protected template GenMessageGetId(uint id) {
immutable string GenMessageGetId
= "public immutable(int) getId() const { \nreturn" ~ id ~ 
";

\n}";
}


Re: Call destructor directly.

2013-10-21 Thread Agustin

On Monday, 21 October 2013 at 07:31:30 UTC, Ali Çehreli wrote:

On 10/20/2013 10:59 PM, Agustin wrote:

> That didn't work, but after reading how emplace works, i had
to make
> some changes.
>
>  public T allocate(T : Object, A...)(auto ref A
arguments) {
>  auto pMemory =
rawAllocate(__traits(classInstanceSize, T),
> T.alignof);

Does rawAllocate still return void*? For classes, emplace 
requires (or at least "also accepts" a slice).


Your code will be simpler if rawAllocate returned a slice:

import std.conv;

void[] rawAllocate(size_t, size_t)
{
static ubyte[1000] buffer;
return buffer;
}

T allocate(T : Object, A...)(auto ref A arguments) {
auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);


return emplace!T(pMemory, arguments);
}

class C
{
this(int i, double d)
{}
}

void main()
{
auto c = allocate!C(42, 1.5);
}

If it has to return void*, you can make a slice from a plain 
pointer with the following syntax:


void * rawAllocate(size_t, size_t)
{
static ubyte[1000] buffer;
return buffer.ptr;
}

import std.stdio;

void main()
{
enum requiredLength = 42;
auto rawPtr = rawAllocate(requiredLength, 16);
auto slice = rawPtr[0..requiredLength];  // <-- slice from 
plain pointer

writeln(slice);
}

Ali


Thanks!, i didn't knew i could do that, void[] sounds like an 
array of nothing :P.


On Monday, 21 October 2013 at 11:48:11 UTC, Benjamin Thaut wrote:

Am 21.10.2013 04:17, schrieb Adam D. Ruppe:

On Monday, 21 October 2013 at 02:06:02 UTC, Agustin wrote:
I'm implementing some custom memory allocator, is possible to 
call an

object destructor directly?



destroy(object);

destroy is in the automatically imported object.dm so you 
don't have to

import anything,

The source code is in dmd2/src/druntime/src/object_.d, there's 
a few
overloads if you are curious how it is implemented. Short 
answer is
there's a pointer to the destructor in the TypeInfo and 
destroy calls it.


Using destroy will zero the entire memory block after 
destroying the object. If you are freeing the memory right 
after destroying this is going to cost you performance.


To avoid this declare:

extern (C) void rt_finalize2(void* p, bool det = true, bool 
resetMemory = true);


and then call

rt_finalize(cast(void*)object, false, false);

Also if you want to give a nice error message in case you are 
calling a construcor that does not exist you should take a look 
at my AllocatorNew function:


https://github.com/Ingrater/druntime/blob/merge64/src/core/allocator.d#L616

Doing it the way emplace does will just result in a error 
message


"Dont know how to initialize a object of type YourObject"

With some meta programming you can get error messages like:

"Dont know how to initialize a object of type YourObject
Available constructors:
this(int, int)
this(float)
this(void*)"

Kind Regards
Benjamin Thaut


I just need to call the destructor of the class since the memory 
of the allocators is released at the end of the application.


// Pre allocate 1GB.
auto pMemory = GC.malloc(1_048_576 * 1000, 
GC.BlkAttr.NONE);


// Allocate a linear allocator of 10MB.
auto pLinearAllocator = new LinearAllocator(1_048_576 * 
10, pMemory);


// Allocates a pool allocator of 50MB.
auto pMemoryBlock = pMemory + 1_048_576 * 10;
auto pPoolAllocator = new 
PoolAllocator!MyComponent(1_048_576 * 50, pMemory + 1_048_576 * 
10);


// Game loop, etc.
// . (When a object is called to release, it won't 
release its memory rather than cache the entry and call the 
object destructor. Releasing the object from GC


// end of game
exit() // Allocators are released here, because GC will 
not find any reference to it, and will call any object destructor 
left.




Re: Call destructor directly.

2013-10-20 Thread Agustin

On Monday, 21 October 2013 at 05:40:13 UTC, Agustin wrote:
On Monday, 21 October 2013 at 05:17:01 UTC, Jonathan M Davis 
wrote:

On Monday, October 21, 2013 05:53:46 Agustin wrote:

On Monday, 21 October 2013 at 03:50:24 UTC, Agustin wrote:
> On Monday, 21 October 2013 at 03:46:33 UTC, Jonathan M Davis
> 
> wrote:

>> On Monday, October 21, 2013 05:07:02 Agustin wrote:
>>> What about constructor?. My current code is:
>>>T allocate(T : Object, A...)(auto ref A arguments) {
>>>
>>> 		auto pMemory = rawAllocate(__traits(classInstanceSize, 
>>> T),
>>> 
>>> T.alignof); // Return void*
>>> 
>>> 		emplace!T(cast(T *)pMemory, arguments);

>>>return cast(T) pMemory;
>>>
>>>}
>>> 
>>> Doesn't seems to work, and i can't find any good 
>>> documentation

>>> about it.
>> 
>> IIRC, the constructor should be name __ctor.
>> 
>> - Jonathan M Davis
> 
> no property 'opCall' for type 'Main.MyClass' :(


Trait allMember return "__ctor", but seems like i cannot call 
it

directly:

(cast(T)pMemory).__ctor(arguments); // Being pMemory void*


If you want to see how to use emplace, I'd advise looking at
std.typecons.RefCounted's implementation:

https://github.com/D-Programming-Language/phobos/blob/master/std/typecons.d#L3505

emplace calls the constructor for you, so I don't know why 
you'd be trying to
call it. But you can look at emplace's implementation if you 
want to see how

to call __ctor.

For structs:
https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L3976

For classes:
https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L4716

I don't think that it'll work if the constructor is private 
though, so maybe

that's your problem.

- Jonathan M Davis


I'm silly the issue was at this line

		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);


emplace(pMemory, arguments);

Correct was

		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);


emplace(&pMemory, arguments);

Thanks guys


That didn't work, but after reading how emplace works, i had to 
make some changes.


public T allocate(T : Object, A...)(auto ref A arguments) {
		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);

assert(pMemory !is null, "Not enought memory on the allocator");

byte[] * pByteMemory = cast(byte[] *) pMemory;
*pByteMemory = typeid(T).init[];

auto pObject = cast(T) pMemory;
static if (is(typeof(pObject.__ctor(arguments
{
pObject.__ctor(arguments);
}
return pObject;
}

That would work.


Re: Call destructor directly.

2013-10-20 Thread Agustin
On Monday, 21 October 2013 at 05:17:01 UTC, Jonathan M Davis 
wrote:

On Monday, October 21, 2013 05:53:46 Agustin wrote:

On Monday, 21 October 2013 at 03:50:24 UTC, Agustin wrote:
> On Monday, 21 October 2013 at 03:46:33 UTC, Jonathan M Davis
> 
> wrote:

>> On Monday, October 21, 2013 05:07:02 Agustin wrote:
>>> What about constructor?. My current code is:
>>>T allocate(T : Object, A...)(auto ref A arguments) {
>>>
>>> 		auto pMemory = rawAllocate(__traits(classInstanceSize, 
>>> T),
>>> 
>>> T.alignof); // Return void*
>>> 
>>> 		emplace!T(cast(T *)pMemory, arguments);

>>>return cast(T) pMemory;
>>>
>>>}
>>> 
>>> Doesn't seems to work, and i can't find any good 
>>> documentation

>>> about it.
>> 
>> IIRC, the constructor should be name __ctor.
>> 
>> - Jonathan M Davis
> 
> no property 'opCall' for type 'Main.MyClass' :(


Trait allMember return "__ctor", but seems like i cannot call 
it

directly:

(cast(T)pMemory).__ctor(arguments); // Being pMemory void*


If you want to see how to use emplace, I'd advise looking at
std.typecons.RefCounted's implementation:

https://github.com/D-Programming-Language/phobos/blob/master/std/typecons.d#L3505

emplace calls the constructor for you, so I don't know why 
you'd be trying to
call it. But you can look at emplace's implementation if you 
want to see how

to call __ctor.

For structs:
https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L3976

For classes:
https://github.com/D-Programming-Language/phobos/blob/master/std/conv.d#L4716

I don't think that it'll work if the constructor is private 
though, so maybe

that's your problem.

- Jonathan M Davis


I'm silly the issue was at this line

		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);


emplace(pMemory, arguments);

Correct was

		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof);


emplace(&pMemory, arguments);

Thanks guys


Re: Call destructor directly.

2013-10-20 Thread Agustin
On Monday, 21 October 2013 at 03:46:33 UTC, Jonathan M Davis 
wrote:

On Monday, October 21, 2013 05:07:02 Agustin wrote:

What about constructor?. My current code is:

T allocate(T : Object, A...)(auto ref A arguments) {
auto pMemory = rawAllocate(__traits(classInstanceSize, T),
T.alignof); // Return void*

emplace!T(cast(T *)pMemory, arguments);
return cast(T) pMemory;
}

Doesn't seems to work, and i can't find any good documentation
about it.


IIRC, the constructor should be name __ctor.

- Jonathan M Davis


no property 'opCall' for type 'Main.MyClass' :(


Re: Call destructor directly.

2013-10-20 Thread Agustin

On Monday, 21 October 2013 at 03:50:24 UTC, Agustin wrote:
On Monday, 21 October 2013 at 03:46:33 UTC, Jonathan M Davis 
wrote:

On Monday, October 21, 2013 05:07:02 Agustin wrote:

What about constructor?. My current code is:

T allocate(T : Object, A...)(auto ref A arguments) {
auto pMemory = rawAllocate(__traits(classInstanceSize, T),
T.alignof); // Return void*

emplace!T(cast(T *)pMemory, arguments);
return cast(T) pMemory;
}

Doesn't seems to work, and i can't find any good documentation
about it.


IIRC, the constructor should be name __ctor.

- Jonathan M Davis


no property 'opCall' for type 'Main.MyClass' :(


Trait allMember return "__ctor", but seems like i cannot call it 
directly:


(cast(T)pMemory).__ctor(arguments); // Being pMemory void*


Re: Call destructor directly.

2013-10-20 Thread Agustin

On Monday, 21 October 2013 at 02:26:03 UTC, Agustin wrote:

On Monday, 21 October 2013 at 02:17:54 UTC, Adam D. Ruppe wrote:

On Monday, 21 October 2013 at 02:06:02 UTC, Agustin wrote:
I'm implementing some custom memory allocator, is possible to 
call an object destructor directly?



destroy(object);

destroy is in the automatically imported object.dm so you 
don't have to import anything,


The source code is in dmd2/src/druntime/src/object_.d, there's 
a few overloads if you are curious how it is implemented. 
Short answer is there's a pointer to the destructor in the 
TypeInfo and destroy calls it.


Thank you :)


What about constructor?. My current code is:

T allocate(T : Object, A...)(auto ref A arguments) {
		auto pMemory = rawAllocate(__traits(classInstanceSize, T), 
T.alignof); // Return void*


emplace!T(cast(T *)pMemory, arguments);
return cast(T) pMemory;
}

Doesn't seems to work, and i can't find any good documentation 
about it.


Re: Call destructor directly.

2013-10-20 Thread Agustin

On Monday, 21 October 2013 at 02:17:54 UTC, Adam D. Ruppe wrote:

On Monday, 21 October 2013 at 02:06:02 UTC, Agustin wrote:
I'm implementing some custom memory allocator, is possible to 
call an object destructor directly?



destroy(object);

destroy is in the automatically imported object.dm so you don't 
have to import anything,


The source code is in dmd2/src/druntime/src/object_.d, there's 
a few overloads if you are curious how it is implemented. Short 
answer is there's a pointer to the destructor in the TypeInfo 
and destroy calls it.


Thank you :)


Call destructor directly.

2013-10-20 Thread Agustin
I'm implementing some custom memory allocator, is possible to 
call an object destructor directly?


For example

void deallocate(T)(T object)
{
  assert(object !is null);

  object.~this();
  rawDeallocate(cast(void *)object);
}


Re: Weird error when compiling.

2013-10-20 Thread Agustin

On Monday, 21 October 2013 at 00:13:59 UTC, bearophile wrote:

Agustin:


Sorry i clicked the post button :(. The full code is:


I don't see your error with the following code, please give the 
code that gives the error, so we can fix the compiler bug:



public class Component {
  


  /// Component's unique id.
  private hash_t id;
  Assertion failure: 'thisval && thisval->op ==

TOKclassreference' on line 4067 in file 'interpret.c' when
compiling this.
  


  /// \brief Default constructor.
  ///
  /// \param[in] id   The id of the component
  


  public this(hash_t id) {
  this.id = id;
  this.active = true;
  this.validated = true;
  }

  
}

public class ComponentDetail(T) : Component {
  


  /// Component's ID as static member.
  public static hash_t ID = typeid(T).toHash;

  


  /// \brief Default constructor.
  


  public this() {
  super(ID);
  }
}

private class InputComponent : ComponentDetail!InputComponent {
}

void main() {
  auto pComponent = new InputComponent();

  writeln(pComponent.getId());
  writeln(InputComponent.ID);
}



Bye,
bearophile


The code is: http://pastebin.com/510YK2Se
Using (LDC 0.12.0-beta 1 Ubuntu): http://pastebin.com/2gAWnYyr
Using (DMD Windows): Assertion failure: 'thisval && thisval->op ==
TOKclassreference' on line 4067 in file 'interpret.c' when
compiling this.


Re: Weird error when compiling.

2013-10-20 Thread Agustin

On Sunday, 20 October 2013 at 22:04:49 UTC, Agustin wrote:

On Sunday, 20 October 2013 at 21:54:37 UTC, Agustin wrote:
On Sunday, 20 October 2013 at 02:14:55 UTC, TheFlyingFiddle 
wrote:
Anyway to evaluate the name of the class and return its hash 
at compile time?


I couldn't find the built in hash unction for strings so i 
used the one from http://dlang.org/hash-map.html as an 
example. More advanced and better hash functions can be found 
online.


public class ComponentDetail(T) : Component {

/// Component's ID as static member.
public static hash_t ID = hash!(T);
}

hash_t hash(T)()
{
  hash_t hash;
  foreach (char c; T.stringof)
  hash = (hash * 9) + c;
  return hash;
}


Works perfectly :), now if i want to implement the same but
rather do something like

template GetHash(string character, hash_t hash = 0, size_t 
index

= 0) {
static if (character[index])
enum GetHash = GetHash(character, hash = (hash * 9) +
character[index], ++index);
else
enum GetHash = hash;
}

How should i implement it?


I came up with something like


template GetHash(string character, hash_t hash = 0, size_t 
index = 0) {

static if (index < character.length)
		enum GetHash = GetHash!(character, (hash * 9) + 
character[index], index + 1);

else
enum GetHash = hash;
}


And the final template is

template Hash(string text, hash_t hash = 0, size_t index = 0) {
static if (index < text.length)
		enum Hash = Hash!(text, (hash ^ text[index]) * 1099511628211UL, 
index + 1);

else
enum Hash = hash;
}

:D


Re: Weird error when compiling.

2013-10-20 Thread Agustin

On Sunday, 20 October 2013 at 21:54:37 UTC, Agustin wrote:
On Sunday, 20 October 2013 at 02:14:55 UTC, TheFlyingFiddle 
wrote:
Anyway to evaluate the name of the class and return its hash 
at compile time?


I couldn't find the built in hash unction for strings so i 
used the one from http://dlang.org/hash-map.html as an 
example. More advanced and better hash functions can be found 
online.


public class ComponentDetail(T) : Component {

/// Component's ID as static member.
public static hash_t ID = hash!(T);
}

hash_t hash(T)()
{
   hash_t hash;
   foreach (char c; T.stringof)
   hash = (hash * 9) + c;
   return hash;
}


Works perfectly :), now if i want to implement the same but
rather do something like

template GetHash(string character, hash_t hash = 0, size_t index
= 0) {
static if (character[index])
enum GetHash = GetHash(character, hash = (hash * 9) +
character[index], ++index);
else
enum GetHash = hash;
}

How should i implement it?


I came up with something like


template GetHash(string character, hash_t hash = 0, size_t index 
= 0) {

static if (index < character.length)
		enum GetHash = GetHash!(character, (hash * 9) + 
character[index], index + 1);

else
enum GetHash = hash;
}


Re: Weird error when compiling.

2013-10-20 Thread Agustin

On Sunday, 20 October 2013 at 02:14:55 UTC, TheFlyingFiddle wrote:
Anyway to evaluate the name of the class and return its hash 
at compile time?


I couldn't find the built in hash unction for strings so i used 
the one from http://dlang.org/hash-map.html as an example. More 
advanced and better hash functions can be found online.


public class ComponentDetail(T) : Component {

/// Component's ID as static member.
public static hash_t ID = hash!(T);
}

hash_t hash(T)()
{
hash_t hash;
foreach (char c; T.stringof)
hash = (hash * 9) + c;
return hash;
}


Works perfectly :), now if i want to implement the same but
rather do something like

template GetHash(string character, hash_t hash = 0, size_t index
= 0) {
static if (character[index])
enum GetHash = GetHash(character, hash = (hash * 9) +
character[index], ++index);
else
enum GetHash = hash;
}

How should i implement it?


Re: Weird error when compiling.

2013-10-19 Thread Agustin

On Sunday, 20 October 2013 at 01:56:39 UTC, TheFlyingFiddle wrote:

public class ComponentDetail(T) : Component {
 


 /// Component's ID as static member.
 public static hash_t ID = typeid(T).toHash;


typeid(T).toHash can not be evaluated by the compiler at 
compile-time.


Placing the ID initalization in a static this should fix the 
problem.


eg.

public static hash_t ID;

static this()
{
  ID = typeid(T).toHash;
}


Anyway to evaluate the name of the class and return its hash at 
compile time?


Re: Weird error when compiling.

2013-10-19 Thread Agustin

On Sunday, 20 October 2013 at 01:41:58 UTC, Agustin wrote:
I'm getting Assertion failure: 'thisval && thisval->op == 
TOKclassreference' on line 4067 in file 'interpret.c' when 
compiling this.


public class Component {

/// Component's unique id.
private hash_t id;


/// \brief Default constructor.
///
/// \param[in] id   The id of the component

public this(hash_t id) {
this.id = id;
this.active = true;
this.validated = true;
}


}

public class ComponentDetail(T) : Component {

/// Component's ID as static member.
public static hash_t ID = typeid(T).toHash;


/// \brief Default constructor.

public this() {
super(ID);
}
}


Sorry i clicked the post button :(. The full code is:

I'm getting Assertion failure: 'thisval && thisval->op ==
TOKclassreference' on line 4067 in file 'interpret.c' when
compiling this.

public class Component {
  
  /// Component's unique id.
  private hash_t id;
  
  
  /// \brief Default constructor.
  ///
  /// \param[in] id   The id of the component
  
  public this(hash_t id) {
  this.id = id;
  this.active = true;
  this.validated = true;
  }

  
}

public class ComponentDetail(T) : Component {
  
  /// Component's ID as static member.
  public static hash_t ID = typeid(T).toHash;

  
  /// \brief Default constructor.
  
  public this() {
  super(ID);
  }
}

private class InputComponent : ComponentDetail!InputComponent {
}

void main() {
  auto pComponent = new InputComponent();

  writeln(pComponent.getId());
  writeln(InputComponent.ID);
}


Weird error when compiling.

2013-10-19 Thread Agustin
I'm getting Assertion failure: 'thisval && thisval->op == 
TOKclassreference' on line 4067 in file 'interpret.c' when 
compiling this.


public class Component {

/// Component's unique id.
private hash_t id;


/// \brief Default constructor.
///
/// \param[in] id   The id of the component

public this(hash_t id) {
this.id = id;
this.active = true;
this.validated = true;
}


}

public class ComponentDetail(T) : Component {

/// Component's ID as static member.
public static hash_t ID = typeid(T).toHash;


/// \brief Default constructor.

public this() {
super(ID);
}
}


Metaprogramming with D.

2013-10-19 Thread Agustin
I'm trying to implement a template Vector and i would like to 
know if this is possible.


My current vector class is:

public class Vector(T, size_t size) {
private T components[size];
}

And i would like to implement a property as this:

@property
public size_t length() const {
return Trait.ExpandFor(size, components, Function(+, (n, 
j))); // Kind of messy but you get my point.

}

instead of doing for(...) over a array i would like to make a 
trait that produce this code


return (x * x + y * y + z * z + ...)



Return a const structure by reference.

2013-10-15 Thread Agustin
I'm having trouble trying to return a const reference of a 
structure.


public struct Structure {
}

public class A {
private Structure structure;

this(Structure structure)
{
this.structure = structure;
}

public ref const Structure getStructure() const {
return structure;
}
}

cannot implicitly convert expression (this.structure) of type 
const(Structure) to Structure


Can't inherit a class and multiple interfaces.

2013-10-11 Thread Agustin
Like the the title says, i cannot inherit a class and have 
interfaces.


class A
{
}

interface B
{
}

class C : A, B -> Error
{
}

I know that D doesn't support multiple classes, but that means i 
cannot mix a class and an interface?


Re: Can't inherit a class and multiple interfaces.

2013-10-11 Thread Agustin

On Saturday, 12 October 2013 at 01:35:48 UTC, Agustin wrote:
Like the the title says, i cannot inherit a class and have 
interfaces.


class A
{
}

interface B
{
}

class C : A, B -> Error
{
}

I know that D doesn't support multiple classes, but that means 
i cannot mix a class and an interface?


Oh i had a typo error, no need to answer me this :D


Re: Traits

2013-10-11 Thread Agustin

On Friday, 11 October 2013 at 19:19:31 UTC, luminousone wrote:
On Friday, 11 October 2013 at 14:09:09 UTC, Gary Willoughby 
wrote:

On Friday, 11 October 2013 at 05:49:38 UTC, luminousone wrote:

On Friday, 11 October 2013 at 04:13:55 UTC, Agustin wrote:
I have a function that needs to check if the template 
provided inherit a class.


For example:

public void function(T, A...)(auto ref A values)
{
// static assert(IsBaseOf(L, T));
}

Check if T inherit class "L". Same result that 
std::is_base_of::value using C++. Any clean way to do 
it, without a dirty hack.


import std.traits;

bool ChildInheritsFromParent( parent, child )( ) {

foreach ( k, t; BaseClassesTuple!child ) {
if( typeid(t) == typeid(parent) )
return true;
}
return false;
}


A simpler way:

import std.stdio;

bool instanceOf(A, B)(B value)
{
return !!cast(A)value;
}

void main()
{
assert(1.instanceOf!(int));
}


Using casts that way won't always be correct, it would be 
better to use reflection in some way if possible.


This is wrong for me because i don't have a value, i just wanted 
to check if a template parameter inherit a class at compile time.


bool instanceOf(A, B)();


Re: Traits

2013-10-11 Thread Agustin

On Friday, 11 October 2013 at 04:35:38 UTC, Ali Çehreli wrote:

On 10/10/2013 09:13 PM, Agustin wrote:

> I have a function that needs to check if the template
provided inherit a
> class.
>
> For example:
>
> public void function(T, A...)(auto ref A values)

function happens to be a keyword. :)

> {
>// static assert(IsBaseOf(L, T));
> }
>
> Check if T inherit class "L". Same result that
std::is_base_of T>::value using C++. Any clean way to do it, without a dirty
hack.

One of the uses of the is expression determines "whether 
implicitly convertible to". It may work for you:


public void foo(T, A...)(auto ref A values)
{
static assert(is (T : L));
}

class L
{}

class LL : L
{}

void main()
{
foo!LL(1, 2.3, "4");
}

Ali


On Friday, 11 October 2013 at 05:45:00 UTC, Jonathan M Davis 
wrote:

On Thursday, October 10, 2013 21:35:37 Ali Çehreli wrote:
One of the uses of the is expression determines "whether 
implicitly

convertible to". It may work for you:

public void foo(T, A...)(auto ref A values)
{
 static assert(is (T : L));
}


Actually, checking for implicit conversion will work directly 
in the template
signature without a template constraint or static assertion. 
e.g.


public void foo(T : L, A...)auto ref A values)
{
}

- Jonathan M Davis


Those work great, thanks a lot!


Traits

2013-10-10 Thread Agustin
I have a function that needs to check if the template provided 
inherit a class.


For example:

public void function(T, A...)(auto ref A values)
{
  // static assert(IsBaseOf(L, T));
}

Check if T inherit class "L". Same result that std::is_base_ofT>::value using C++. Any clean way to do it, without a dirty hack.


Re: Scope variables.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 23:18:13 UTC, Justin Whear wrote:

On Tue, 08 Oct 2013 01:01:43 +0200, Agustin wrote:
Doesn't ref means i'm passing the parameter by reference 
instead of by
value?. Isn't "a" being copied when calling func?, or does D 
always pass

by reference when using classes and structures?


Class instances are by reference already, structs are by value.
 For
further comparison, please see the table here:
http://dlang.org/struct.html


Thank you!.


Re: Scope variables.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 22:57:17 UTC, Ali Çehreli wrote:

On 10/07/2013 03:52 PM, Agustin wrote:

On Monday, 7 October 2013 at 19:59:09 UTC, Agustin wrote:

On Monday, 7 October 2013 at 19:58:21 UTC, Agustin wrote:

I'm having a hard time trying to use "scoped".

public T callEvent(T, A...)(auto ref A args) const
{
T pEvent = scoped!T(forward!args);
postEvent(pEvent, typeid(T).toHash);
return pEvent;
}

private void postEvent(ref Event event, Event.ID type) const
{

}

src\event\EventManager.d(37): Error: function
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event,
uint type) const is not callable using argument types 
(MyEvent,uint)

src\event\EventManager.d(37): Error: function
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event,
uint type) const is not callable using argument types 
(MyEvent,uint)

const
src\event\EventManager.d(37): Error: cast(Event)pEvent is 
not an lvalue



callEvent!MyEvent(); Being MyEvent a subclass of Event.


So i found out that i cannot do this, may i ask why?

public class A
{
  int x = 0;
}

public class B : A
{
}

void func(ref A a)
{
}

void main()
{
  B b = new B();
  func(b);
}


Since classes are already references, you would normally pass 
A, not 'ref A'.


If you really want to pass 'ref A', perhaps you want to change 
the actual object that an A is referring to:


public class C : A
{}

void func(ref A a)
{
a = new C;// <-- A reason for taking 'ref A'
}

However, that would upset the caller, which thinks it has a 
reference to a B object:


void main()
{
  B b = new B();
  func(b);// <-- Oops! Not a B anymore?
}

Ali


Doesn't ref means i'm passing the parameter by reference instead 
of by value?. Isn't "a" being copied when calling func?, or does 
D always pass by reference when using classes and structures?


Re: Scope variables.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 19:59:09 UTC, Agustin wrote:

On Monday, 7 October 2013 at 19:58:21 UTC, Agustin wrote:

I'm having a hard time trying to use "scoped".

public T callEvent(T, A...)(auto ref A args) const
{
 T pEvent = scoped!T(forward!args);
 postEvent(pEvent, typeid(T).toHash);
 return pEvent;
}

private void postEvent(ref Event event, Event.ID type) const
{
 
}

src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event, uint type) const is not callable using argument types 
(MyEvent,uint)
src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event, uint type) const is not callable using argument types 
(MyEvent,uint) const
src\event\EventManager.d(37): Error: cast(Event)pEvent is not 
an lvalue



callEvent!MyEvent(); Being MyEvent a subclass of Event.


So i found out that i cannot do this, may i ask why?

public class A
{
  int x = 0;
}

public class B : A
{
}

void func(ref A a)
{
}

void main()
{
  B b = new B();
  func(b);
}


Re: Get unique id of a class type.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 19:24:32 UTC, Agustin wrote:

On Monday, 7 October 2013 at 19:07:19 UTC, simendsjo wrote:

On Monday, 7 October 2013 at 18:55:58 UTC, Agustin wrote:
I'm looking a way to get the unique id of a class. I'm able 
to do

this in C++ using type_info::hash_code().

void function(T) {
  auto id = typeid(T).getHash(); // Something like this?

  // I know i could write this but seems ugly to me :/
  auto id = typeid(string).getHash(typeid(T).name);

  // Or maybe even better.
  auto id = typeid(T).id; // ID is not a number but a class 
for

storing
}


Have you tried toHash()?
https://github.com/D-Programming-Language/druntime/blob/master/src/object_.d#L211


I Think that would return the hash of every member of a class, 
rather than just the hash of the class name


Nevermind, i just saw the link you gave me, thanks a lot!.


Scope variables.

2013-10-07 Thread Agustin

I'm having a hard time trying to use "scoped".

public T callEvent(T, A...)(auto ref A args) const
{
  T pEvent = scoped!T(forward!args);
  postEvent(pEvent, typeid(T).toHash);
  return pEvent;
}

private void postEvent(ref Event event, Event.ID type) const
{
  
}

src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event event, 
uint type) const is not callable using argument types 
(MyEvent,uint)
src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event event, 
uint type) const is not callable using argument types 
(MyEvent,uint) const
src\event\EventManager.d(37): Error: cast(Event)pEvent is not an 
lvalue


Re: Scope variables.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 19:58:21 UTC, Agustin wrote:

I'm having a hard time trying to use "scoped".

public T callEvent(T, A...)(auto ref A args) const
{
  T pEvent = scoped!T(forward!args);
  postEvent(pEvent, typeid(T).toHash);
  return pEvent;
}

private void postEvent(ref Event event, Event.ID type) const
{
  
}

src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event, uint type) const is not callable using argument types 
(MyEvent,uint)
src\event\EventManager.d(37): Error: function 
ghrum.event.EventManager.EventManager.postEvent (ref Event 
event, uint type) const is not callable using argument types 
(MyEvent,uint) const
src\event\EventManager.d(37): Error: cast(Event)pEvent is not 
an lvalue



callEvent!MyEvent(); Being MyEvent a subclass of Event.


Re: Get unique id of a class type.

2013-10-07 Thread Agustin

On Monday, 7 October 2013 at 19:07:19 UTC, simendsjo wrote:

On Monday, 7 October 2013 at 18:55:58 UTC, Agustin wrote:
I'm looking a way to get the unique id of a class. I'm able to 
do

this in C++ using type_info::hash_code().

void function(T) {
   auto id = typeid(T).getHash(); // Something like this?

   // I know i could write this but seems ugly to me :/
   auto id = typeid(string).getHash(typeid(T).name);

   // Or maybe even better.
   auto id = typeid(T).id; // ID is not a number but a class 
for

storing
}


Have you tried toHash()?
https://github.com/D-Programming-Language/druntime/blob/master/src/object_.d#L211


I Think that would return the hash of every member of a class, 
rather than just the hash of the class name


Get unique id of a class type.

2013-10-07 Thread Agustin

I'm looking a way to get the unique id of a class. I'm able to do
this in C++ using type_info::hash_code().

void function(T) {
auto id = typeid(T).getHash(); // Something like this?

// I know i could write this but seems ugly to me :/
auto id = typeid(string).getHash(typeid(T).name);

// Or maybe even better.
auto id = typeid(T).id; // ID is not a number but a class for
storing
}


Designing an API with D.

2013-09-30 Thread Agustin

Hello, i'm trying to make a library and i would like to use that
library on a separated application using only interfaces. I know
how to do it using C++, but i don't known using D. Can anyone
help me?

Project #1
include/*.d -> These are interfaces.
src/*.d -> Implementation code using those interface.

Project #2
src/*.d -> Its code using only Project #1's include folder
without implementation code.

Thanks!


Re: Question about Mixin.

2013-06-19 Thread Agustin

On Wednesday, 19 June 2013 at 23:35:16 UTC, Ali Çehreli wrote:

On 06/19/2013 04:29 PM, Agustin wrote:
Hello guys, my question is, its possible to write a mixin in a 
class,
then if that class is inherited, the mixin will be written 
again instead

of written the mixin again in the class child, for example:

Class A(T)
{
 mixin(WriteFunctionFor!(A));
}

Class B : A(B)
{
  ... -> mixin is written for B without need to write 
("mixin(Write...))")

}

Class C : A(C)
{
  ... -> mixin is written for C without need to write 
("mixin(Write...))")

}


Yes:

import std.stdio;

template WriteFunctionFor(T)
{
T data;

void foo()
{
writefln("I am working with a %s.", T.stringof);
}
}

class A(T)
{
mixin WriteFunctionFor!T;
}

class B : A!B
{}

class C : A!C
{}

void main()
{
auto b = new B();
b.foo();

auto c = new C();
c.foo();
}

The output:

I am working with a B.
I am working with a C.

Ali


Thanks!, now i'm trying to do that but its not working :(.

template Eventable(T) {
final static __gshared public HandlerList!T getHandler() {
if( handler_ is null ) {
handler_ = new HandlerList!T();
}
return handler_;
}
}

public class EventTemplate(T) : Event {
mixin Eventable!T;
}

class TestEvent : EventTemplate!(TestEvent) {
double x = 0.0;
}

TestEvent.getHandler() -> wont work.


Re: Question about Mixin.

2013-06-19 Thread Agustin

On Thursday, 20 June 2013 at 00:20:36 UTC, Agustin wrote:

On Wednesday, 19 June 2013 at 23:35:16 UTC, Ali Çehreli wrote:

On 06/19/2013 04:29 PM, Agustin wrote:
Hello guys, my question is, its possible to write a mixin in 
a class,
then if that class is inherited, the mixin will be written 
again instead

of written the mixin again in the class child, for example:

Class A(T)
{
mixin(WriteFunctionFor!(A));
}

Class B : A(B)
{
 ... -> mixin is written for B without need to write 
("mixin(Write...))")

}

Class C : A(C)
{
 ... -> mixin is written for C without need to write 
("mixin(Write...))")

}


Yes:

import std.stdio;

template WriteFunctionFor(T)
{
   T data;

   void foo()
   {
   writefln("I am working with a %s.", T.stringof);
   }
}

class A(T)
{
   mixin WriteFunctionFor!T;
}

class B : A!B
{}

class C : A!C
{}

void main()
{
   auto b = new B();
   b.foo();

   auto c = new C();
   c.foo();
}

The output:

I am working with a B.
I am working with a C.

Ali


Thanks!, now i'm trying to do that but its not working :(.

template Eventable(T) {
final static __gshared public HandlerList!T getHandler() {
if( handler_ is null ) {
handler_ = new HandlerList!T();
}
return handler_;
}
}

public class EventTemplate(T) : Event {
mixin Eventable!T;
}

class TestEvent : EventTemplate!(TestEvent) {
double x = 0.0;
}

TestEvent.getHandler() -> wont work.


 public class EventTemplate(T) : Event {
 mixin Eventable!T;
 protected __gshared HandlerList!T handler_;
 }


Question about Mixin.

2013-06-19 Thread Agustin
Hello guys, my question is, its possible to write a mixin in a 
class, then if that class is inherited, the mixin will be written 
again instead of written the mixin again in the class child, for 
example:


Class A(T)
{
 mixin(WriteFunctionFor!(A));
}

Class B : A(B)
{
  ... -> mixin is written for B without need to write 
("mixin(Write...))")

}

Class C : A(C)
{
  ... -> mixin is written for C without need to write 
("mixin(Write...))")

}


Re: Error: cannot implicitly convert expression

2013-06-18 Thread Agustin

On Tuesday, 18 June 2013 at 21:43:17 UTC, Agustin wrote:

On Tuesday, 18 June 2013 at 21:39:35 UTC, Agustin wrote:

Hello!, i'm having a problem and i don't know how to fix it :(.

/**
* Define a common structure for any event.
*
* @author Wolftein 
*/
public class Event(T) {

private bool cancelled_;
private shared static HandlerList!T handler_;

/**
 * Return if the event was cancelled.
 */
final public bool isCancelled() {
return cancelled_;
}

/**
 * Set the cancelled flag.
 *
 * @param cancelled the cancelled flag value
 */
final public void setCancelled(bool cancelled) {
cancelled_ = cancelled;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action.
 */
final public HandlerList!T getHandler() {
return handler_;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action. This function is
 * static, so can be called like Template.getHandler()
 */
final public HandlerList!T getHandler() {
return handler_;
}
}

---
class PlayerLoginEvent : Event!(PlayerLoginEvent) {
int x;
}

src\Event\Event.d(41): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList
src\Event\Event.d(51): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList



The last function is:

final static public HandlerList!T getHandler() {
return handler_;
}


I just fixed by replacing shared with __gshared. Another issue 
that i have is that if i have.


public class Event(T) {
static public HandlerList!T getHandler() {
if( handler_ is null ) {
handler_ = new HandlerList!T();
}
return handler_;
}
}

public class MyPlayerEvent : Event!MyPlayerEvent {
}

MyPlayerEvent.getHandler(); -> Error: need 'this' for getHandler 
type HandlerList().


Thanks in advance!


Re: Error: cannot implicitly convert expression

2013-06-18 Thread Agustin

On Tuesday, 18 June 2013 at 21:39:35 UTC, Agustin wrote:

Hello!, i'm having a problem and i don't know how to fix it :(.

/**
 * Define a common structure for any event.
 *
 * @author Wolftein 
 */
public class Event(T) {

private bool cancelled_;
private shared static HandlerList!T handler_;

/**
 * Return if the event was cancelled.
 */
final public bool isCancelled() {
return cancelled_;
}

/**
 * Set the cancelled flag.
 *
 * @param cancelled the cancelled flag value
 */
final public void setCancelled(bool cancelled) {
cancelled_ = cancelled;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action.
 */
final public HandlerList!T getHandler() {
return handler_;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action. This function is
 * static, so can be called like Template.getHandler()
 */
final public HandlerList!T getHandler() {
return handler_;
}
}

---
class PlayerLoginEvent : Event!(PlayerLoginEvent) {
int x;
}

src\Event\Event.d(41): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList
src\Event\Event.d(51): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList



The last function is:

final static public HandlerList!T getHandler() {
return handler_;
}


Error: cannot implicitly convert expression

2013-06-18 Thread Agustin

Hello!, i'm having a problem and i don't know how to fix it :(.

/**
 * Define a common structure for any event.
 *
 * @author Wolftein 
 */
public class Event(T) {

private bool cancelled_;
private shared static HandlerList!T handler_;

/**
 * Return if the event was cancelled.
 */
final public bool isCancelled() {
return cancelled_;
}

/**
 * Set the cancelled flag.
 *
 * @param cancelled the cancelled flag value
 */
final public void setCancelled(bool cancelled) {
cancelled_ = cancelled;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action.
 */
final public HandlerList!T getHandler() {
return handler_;
}

/**
 * Gets the unique handler of the event, the handler
 * contains a list of delegates to be executed when
 * the event triggers an action. This function is
 * static, so can be called like Template.getHandler()
 */
final public HandlerList!T getHandler() {
return handler_;
}
}

---
class PlayerLoginEvent : Event!(PlayerLoginEvent) {
int x;
}

src\Event\Event.d(41): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList
src\Event\Event.d(51): Error: cannot implicitly convert 
expression (handler_) of type shared(HandlerList) to 
ghrum.event.HandlerList.HandlerList!(PlayerLoginEvent).HandlerList


Re: Error: cannot uniquely infer foreach argument types

2013-06-14 Thread Agustin

On Friday, 14 June 2013 at 17:17:46 UTC, bearophile wrote:

Agustin:

Hello, i'm trying to create a library with utilities classes 
like containers using Java API.


The problem with this is that most Phobos works with ranges...



Could anyone help me?


Maybe your code has multiple problems. If you want a precise 
answer, then give a complete little program. But a possible 
problem is in the opApply:


int opApply(int delegate(ref E) delegation);

If you want to use:

foreach (i, e; it) {

Then you need to put both in the opApply (or add a second 
opApply overload), something like:


int opApply(int delegate(ref int, ref E) delegation);

Bye,
bearophile


int opApply(int delegate(ref int, ref E) delegation);

Works!, thanks.


Error: cannot uniquely infer foreach argument types

2013-06-14 Thread Agustin
Hello, i'm trying to create a library with utilities classes like 
containers using Java API. Could anyone help me?


public interface Iterator(E) {
   bool hasNext();
   E next();
   void remove();
   int opApply(int delegate(ref E) delegation);
}

public class AbstractCollection(E) : Collection!E {

   .

E[] toArray(E[] dst = null) {
size_t count = size();
if( dst.length < count ) {
dst.length = count;
}
Iterator!E it = iterator();
	foreach(int i,E e; it) { -> Error: cannot uniquely infer 
foreach argument types

dst[i] = e;
}
return dst[0 .. count];
}

   .

}


Re: Static member inside a class.

2013-06-13 Thread Agustin
On Thursday, 13 June 2013 at 19:59:11 UTC, Steven Schveighoffer 
wrote:
On Thu, 13 Jun 2013 15:47:22 -0400, Agustin 
 wrote:


I would like to know if static members are shared between 2 
library. For example:


Class A
{
 static uint var;
}

From Library A:

A::var = 3;

From Library B:

if( A::var == 3 )
  ...

Its this possible? if not, its any way to make it happend?


It's possible, and works just like you have it (syntax is 
slightly different, use A.var)


However, static means "thread local"  So you can't access the 
same A.var from multiple threads.


To access from multiple threads, declare var like:

shared static uint var;

-Steve


On Thursday, 13 June 2013 at 20:00:59 UTC, w0rp wrote:

On Thursday, 13 June 2013 at 19:47:23 UTC, Agustin wrote:
I would like to know if static members are shared between 2 
library. For example:


Class A
{
static uint var;
}

From Library A:

A::var = 3;

From Library B:

if( A::var == 3 )
 ...

Its this possible? if not, its any way to make it happend?


The members are shared between different modules, yes. You use 
. instead of :: for scope resolution. You can also initialise a 
few things in a static constructors at class scope...


class A {
static uint var;

static this() {
var = 3;
}
}

Or at module scope...

class A {
static uint var;
}

static this() {
A.var = 3;
}

You should note that the data isn't shared between threads by 
default, but that's another detail. You can also usually 
produce a design that uses non-static data instead of static 
data.


Thanks for taking the time to explain me, i'm currently doing an 
event system for my game, and i came out with the idea of an 
Event System.


\ [1] - Map each event to an ID with their name.

Event
{
 .
}

PlayerLoginEvent : Event
{
 .
}

EventManager.callEvent(PlayerLoginEvent(Player));
EventManager.registerListener!PlayerLoginEvent(delegate)
{
  Map[ID(PlayerLoginEvent.Name)] ~ delegate;
}

\ [2] - Have a static list inside each event class.

PlayerLoginEvent : Event
{
  Static Delegates;

  
}

EventManager.registerListener!PlayerLoginEvent(delegate)
{
  // T -> Template
  T.Delegates ~ delegate; // No lookup in a associative array.
}

So thats why i was asking about the static member, thanks!.


Static member inside a class.

2013-06-13 Thread Agustin
I would like to know if static members are shared between 2 
library. For example:


Class A
{
 static uint var;
}

From Library A:

A::var = 3;

From Library B:

if( A::var == 3 )
  ...

Its this possible? if not, its any way to make it happend?