How to declare a template type as parameter to functions
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 3 16:39:41 PST 2014
On Tue, Nov 04, 2014 at 12:29:54AM +0000, Domingo via Digitalmars-d-learn wrote:
[...]
> Like the "simple" function that I tried to write to not duplicate code
> is not worth because I'll need to write one for each type of
> MongoCursor:
>
> 1 - MongoCursor!(Bson, Bson, typeof(null))
> 2 - MongoCursor!(Bson, Bson, Bson)
> 3 - MongoCursor!(Bson, Bson, int[string])
>
> protected void sendCollectionListAsDataArrayJson2(T)(T
> collection_list, HTTPServerResponse res)
>
> What will be "T" on the function above ?
T is a placeholder identifier that can be any accepted type. For
example:
// Note: only one copy of func needs to be written
void func(T)(T x) {
writeln("%s", x);
}
void main() {
func(1); // you can pass an int
func("x"); // or a string
func(1.0); // or a float
struct S {}
S s;
func(s); // or a struct
}
> If I need to write one for each of then My intent of prevent
> duplicated code is dead.
> The function only use code that should work on any combination of
> MongoCursor template.
That's exactly what you need a template function for. Instead of writing
15 copies of the function, one for each different MongoCursor type, you
write only a single function that takes a generic parameter, for
example:
void sendCollection(T)(MongoCursor!(Bson, Bson, T) list,
HttpRequest req)
{
...
}
...
HttpRequest req;
MongoCursor!(Bson, Bson, int) x1;
MongoCursor!(Bson, Bson, float) x2;
MongoCursor!(Bson, Bson, int[string]) x3;
// N.B.: you can pass any matching type
sendCollection(x1, req);
sendCollection(x2, req);
sendCollection(x3, req);
Of course, the foregoing assumes that only the last parameter of
MongoCursor varies. If you need to take MongoCursor of *any* combination
of parameters, you can use multiple template parameters, e.g.:
// Now this will work with MongoCursor!(Bson, Bson,
// int[string]), MongoCursor!(Json, Bson, Bson),
// MongoCursor!(string, int, float), etc..
void sendCollection(T,U,V)(MongoCursor!(T,U,V) list, ...) {
...
}
T
--
Those who don't understand D are condemned to reinvent it, poorly. -- Daniel N
More information about the Digitalmars-d-learn
mailing list