Q about template function overloads
Bill Baxter
dnewsgroup at billbaxter.com
Sun Dec 17 17:14:34 PST 2006
Given a templated array-like class that looks like:
class Array(T)
{ ... }
How can I write a two overloaded versions of func, one which takes T[]
and one which takes Array!(T), and have both return an Array!(T)?
In this case the Dummy trick[1] doesn't seem to be of much use.
[1] http://d.puremagic.com/issues/show_bug.cgi?id=337
That only seems to work when the Dummy is a specific type, not a
parameterized type.
Am I stuck with static if's in this case?
What I'd like to write:
---------
// clean simple obvious, but doesn't compile
Array!(T) func(T)(Array!(T) a)
{
...
}
Array!(T) func(T)(T[] a)
{
...
}
---------
What I think I have to write instead
----------
// Not as clear or correct, but compiles
template _ArrayTForT(T)
{
static if( is( T S: S[]) ) {
alias ndarray!(S) _ArrayTForT;
}
else { // really should check here that T==Array!(S) for some S
alias T _ArrayTForT;
}
}
_ArrayTForT!(T) diag(T)(T v) {
alias _ArrayTForT!(T) ArrayT;
static if( is( T S: S[]) )
{
writefln("T is a D array");
return new ArrayT;
}
else { // should be more specific check!
writefln("T is (maybe) an Array");
return new ArrayT;
}
}
-------------
Also how do I write the equivalent of this:
static if( is( T S: S[]) ) {
alias Array!(S) _ArrayTForT;
}
For the case where T is a user-defined array type:
/// doesn't work!
static if( is( T S: Array!(S)) ) {
alias Array!(S) _ArrayTForT;
}
It really shouldn't just be an "else" catch-all in the code above. It
should be checking for an instantiation of Array!().
--bb
More information about the Digitalmars-d-learn
mailing list