template function. test array parameter length
Philippe Sigaud
philippe.sigaud at gmail.com
Sat Jan 5 14:38:30 PST 2013
On Sat, Jan 5, 2013 at 10:50 PM, ref2401 <refactor24 at gmail.com> wrote:
> I have a template function that must work with an array of float values.
> something like this:
>
> void foo(T : A[], A)(auto ref T arg)
> if(is(A == float))
> {
> ...
> }
>
> Array may be static or dynamic. But the length of the array must be 16 or
> 32. How can i test length value?
>
For a dynamic array, its type is T[] and the length is a known only at
runtime (by definition). You can test it with a runtime test, but not with
a template constraint.
For a static array T[n], n is part of the type so you can indeed filter the
bad ones during compilation.
Using std.traits and std.range:
import std.array;
import std.traits;
import std.range;
void foo(T)(auto ref T arg)
if ( isDynamicArray!T && is(ElementType!T == float)
|| isStaticArray!T && (T.length == 16 || T.length == 32) &&
is(ElementType!T == float))
{}
void main()
{
float[] dynamicArr;
float[3] staticArr1 = [0.0,1.0,2.0];
float[16] staticArr2;
foo(dynamicArr);
//foo(staticArr1); // fails
foo(staticArr2);
}
Or, if you prefer using the is() expression:
void bar(T)(auto ref T arg)
if ( is(T _ == U[], U)
|| is(T _ == U[n], U, size_t n) && (n == 16 || n == 32))
{}
void main()
{
float[] dynamicArr;
float[3] staticArr1 = [0.0,1.0,2.0];
float[16] staticArr2;
bar(dynamicArr);
//bar(staticArr1); // fails
bar(staticArr2);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20130105/2332b576/attachment.html>
More information about the Digitalmars-d-learn
mailing list