Method overloading without Type2Type
Benjamin Thaut
code at benjamin-thaut.de
Tue Apr 26 23:31:54 PDT 2011
Am 26.04.2011 22:41, schrieb Philippe Sigaud:
> On Tue, Apr 26, 2011 at 22:06, Benjamin Thaut<code at benjamin-thaut.de> wrote:
>> The Problem with that version is, that the code that is generated looks like
>>
>> void main(string[] args){
>> auto test = new Foo!(int,float,double,short,byte)();
>> test.print();
>> test.echo!double(double.init);
>> test.echo!short(short.init);
>> }
>>
>> If the types that are used, are no simple data types, but rather large
>> structs, they are copied on every function call. Thats exactly what I want
>> to avoid. The Type2Type template has a size of 0, thats why I'm using that
>> in the first place.
>
> In that case, just use echo(U)() { ...}, like this:
>
> import std.stdio;
>
> class Foo(T,R...) : Foo!(R) {
> public void print(){
> writefln(T.stringof);
> super.print();
> }
>
> public void echo(U)() {
> writefln(U.stringof);
> }
> }
>
> class Foo(T){
> public void print(){
> writefln("end: " ~ T.stringof);
> }
>
> public void echo(U)() {
> writefln(U.stringof);
> }
> }
>
> void main(string[] args){
> auto test = new Foo!(int,float,double,short,byte)();
> test.print();
>
> test.echo!double;
> test.echo!short;
> }
>
> What's your global goal with this construction? What are you trying to achieve?
struct Foo {...}
struct Bar {...}
void* poolAllocate(size_t sz){...};
abstract class Allocator(T){
//needs to be implemented by user to fill obj with data
public abstract void init(ref T obj);
public void make(Type2Type!(T)){
void* ptr = poolAllocate(T.sizeof);
T* obj = emplace!(T)(ptr[0..T.sizeof]);
init(*obj);
}
abstract void produce();
}
abstract class Allocator(T,R...) : Allocator!(R) {
//needs to be implemented by user to fill obj with data
public abstract void init(ref T obj);
alias Allocator!(R).make make;
public void make(Type2Type!(T)){
void* ptr = poolAllocate(T.sizeof);
T* obj = emplace!(T)(ptr[0..T.sizeof]);
init(*obj);
}
}
class UserImpl : Allocator!(Foo,Bar){
override void init(ref Foo obj){
//fill Foo with data
}
override void init(ref Bar obj){
//fill Bar with data
}
override void produce(){
for(...){
make(Type2Type!(Foo));
}
for(...){
make(Type2Type!(Bar));
}
}
}
I do this to hide away allocation and pointer arithmetic from the user.
--
Kind Regards
Benjamin Thaut
More information about the Digitalmars-d-learn
mailing list