Q about template for matching arrays

Bill Baxter dnewsgroup at billbaxter.com
Thu Feb 1 06:25:56 PST 2007

Kirk McDonald wrote:
> Bill Baxter wrote:
>> I'd like to write a template function something like:
>>    T foo(T,S)(S x)
>> that takes arrays of various kinds and returns an element of the base 
>> type (well really something derived from the base type, but that 
>> part's easy).
>> The trick is that what I'd really like is for it be able to be used in 
>> all of the following ways:
>>   // IFTI
>>   foo(3)    // T=int S=int
>>   foo([3])  // T=int S=int[]
>>   foo([[3]])  // T=int S=int[][]
>>   foo([[[3]]])  // T=int S=int[][][]
>>   ... etc
>>   // Base type explicit
>>   foo!(float)(3)  // T=float S=float
>>   foo!(float)([3])  // T=float S=float[]
>>   foo!(float)([[3]])  // T=float S=float[][]
>>   ... etc
>> It's easy if you say you have to call it like foo!(float[][])([[3]]), 
>> but that's annoying.
>> Any bright ideas?
>> --bb
> This only works for dynamic arrays, but:
> typeof(T.init[0]) foo(T)(T x) {}

Just getting the base type of the array is not what I'm after.

The ultimate goal is to write something that's as close as possible to 
NumPy's 'asarray' function, a function which takes a wide range of input 
types and returns an n-dimensional "Array!(Type)" object built from that 

The trick is that in some cases I might like to coerce the data type.  Like

but with the above asarray(T)(T x) declaration that gives an error like 
"int[][] is not a cfloat".

I suspect I may just have to settle for two versions like asarray(T)(T 
x) and
     template asarray_of_type(AT) { asarray_of_type(T)(T x) {} }

Yeh, that doesn't seem so bad actually.


More information about the Digitalmars-d-learn mailing list