Template constraints in D
Bill Baxter
dnewsgroup at billbaxter.com
Sat Jun 21 04:55:36 PDT 2008
Walter Bright wrote:
> Bill Baxter wrote:
>> Maybe you should provide an example somewhere of how to translate this
>> basic C++0x example into D:
>>
>> ----
>> auto concept LessThanComparable<typename T> {
>> bool operator<(T, T);
>> };
>>
>> template<LessThanComparable T>
>> const T& min(const T& x, const T& y) {
>> return x < y? x : y;
>> }
>> ----
>
>
> See the isAddable example.
A more natural way to declare required functions would be nice.
First of all, about the isAddable example, can't you just use T.init
instead of writing an anonymous delegate? Like
__traits(compiles, T.init + T.init)
Anyway, for a less trivial example I think that becomes pretty
cumbersome. E.g.:
concept Stack<typename X> {
typename value_type;
void push(X&, const value_type&);
void pop(X&);
value_type top(const X&);
bool empty(const X&);
};
is going to translate to something like this?:
template Stack(T)
{
const Stack =
is(T.value_type) &&
__traits(compiles, (T t, T.value_type v) { push(t, v); }) &&
__traits(compiles, (T t) { pop(t); }) &&
__traits(compiles, (T t) { top(t); }) &&
is(typeof(top(T.init))==T.value_type) &&
__traits(compiles, (T t) { empty(t) }) &&
is(typeof(empty(T.init))==bool);
}
I hope you can work out a way to give this a more natural syntax, like
Concepts will have in C++0x.
----
An unrelated comment is that I don't think it is relevant or respectful
to compare the lengths of the specs. The spec for Concepts that you
link to includes many many more in depth examples than the D spec does.
It's an apples vs oranges comparison. So 5 pages vs 49 pages really
doesn't have much meaning at all.
--bb
More information about the Digitalmars-d
mailing list