Template namespaces - Obsolete?
Kirk McDonald
kirklin.mcdonald at gmail.com
Wed Sep 19 12:47:35 PDT 2007
Janice Caron wrote:
> Now that we can do:
> class A(T);
> struct A(T);
> union A(T);
> T func(T)(T x);
> static int func(int n);
> ...
> etc.
>
> Is there any need, any more, for the old fashioned
>
> template t(T)
> {
> int f();
> int g();
> }
>
> and having to refer to t!(T).f() and t!(T).g() ?
>
> I almost think it would suffice to complete the new notation with
> obvious extensions like
> typedef(T) something t; /* == template t(T) { typedef something t; } */
> alias(T) something t; /* == template t(T) { typedef something t; } */
> enum(T) t : T {...}; /* == template t(T) { enum t : T {...}; } */
> int a(int N)[N]; /* == template a(int N) { int a[N]; } */
>
> (Not too sure about the usefulness of that last one, but I include if
> for completion).
>
> and then deprecate the old namespace notation.
>
> The namespace notation is very useful for defining mixins though, and
> perhaps that has now become its primary purpose. If that functionality
> is ever replaced by "macro", what then?
The template namespace notation is still very useful. Pyd uses it
extensively. Some examples are:
// A templated AA.
template wrapped_gc_references(T) {
PyObject*[T] wrapped_gc_references;
}
// A template for deriving the signatures of a property, given an
// alias to it:
template property_parts(alias p) {
// This may be either the getter or the setter
alias typeof(&p) p_t;
alias ParameterTypeTuple!(p_t) Info;
// This means it's the getter
static if (Info.length == 0) {
alias p_t getter_type;
// The setter may return void, or it may return the newly
// set attribute.
alias typeof(p(ReturnType!(p_t).init))
function(ReturnType!(p_t)) setter_type;
// This means it's the setter
} else {
alias p_t setter_type;
alias Info[0] function() getter_type;
}
}
It also uses this idiom extensively: An extern(C) function inside a
template.
template wrapped_repr(T, alias fn) {
extern(C)
PyObject* repr(PyObject* self) {
return exception_catcher(delegate PyObject*() {
return method_wrap!(T, fn, char[] function()).func(self, null);
});
}
}
Things can get weird if you declare an extern(C) function template. (Or
at least they used to; I haven't tried it in ages. This idiom also dates
back to before the short-hand syntax for function templates existed,
although this particular code is fairly new.)
--
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
More information about the Digitalmars-d
mailing list