简体   繁体   中英

In typescript, how to write a function to handle arbitrary dimensional array (e.g.:Array<number>,Array<Array<number>>,…)?

In C++, I can write a template function:

#include <stdio.h>
#include <vector>
template <typename V>
void f(V& v){
    for(auto& e : v){
        f(e);
    }
    printf("\n");
}

template <>
void f(int& v){
    printf("%d ",v);
}

to handle any dimensions of vector in vector(eg:vector< int>,vector< vector< int>>,vector< vector< vector< int>>>,...):

int main(){
    std::vector<int> v1={1,2};
    f(v1);
    std::vector<std::vector<int> > v2={{3,4},{5,6,7}};
    f(v2);
    return 0;
};

is such a type of function like this:

let v1 : Array<number>=[1,2];
f<Array<number>>(v1);

let v2 : Array<Array<number>>=[[3,4],[5,6,7]];
f<Array<Array<number>>>(v2);

also possible in typescript? I try something like:

f<V>(v : V){
  for(let e in v){
    this.f(e);
  }
}

f<>(v : number){
}

but the error says

Duplicate function implementation.

and I believe I may be in wrong approach

In C++ you are full specializing the function template.
Anyway, generics in typescript are more like generics in Java or C#, not that much similar to templates in C++.
You cannot define full specializations.

You can only have one function with the same name, so you need to reconcile both portions into the same function. In this case, a simple check for an array should be sufficient.

f(v: any)
{
  if (Array.isArray(v))
    for (let e in v)
      this.f(e);
  else
    doSomething(v);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM