使用模板在C++中映射函数

Raf*_*ini 3 c++ templates map

我正在尝试用C++学习模板,我尝试的其中一件事就是编写一个地图函数,就像你通常在函数式语言中找到的那样.这个想法是这样的:

template <class X> X * myMap(X * func(X), X * array, int size)
    {
      X * temp;
      for(int i = 0, i < size, i++) {temp[i] = (*func)(array[i]);}
      return temp;
    }
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用它时:

int test(int k) { return 2 * k;}
int main(void)
{
   int k[5] = {1,2,3,4,5};
   int *q = new int[5];
   q = myMap(&test, k, 5);
   for(int i=0; i<5; i++) {cout << q[i];}
   delete [] q;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译时出现类型不匹配错误:

 main.cpp:25: error: no matching function for call to ‘myMap(int (*)(int), int [5], int)’
Run Code Online (Sandbox Code Playgroud)

我试着把它改成:

int main(void)
{
   int *k = new int[5];
   int *q = new int[5];
   for(int i=0; i<5;i++) {k[i] = i;}
   q = myMap(&test, k, 5);
   for(int i=0; i<5; i++) {cout << q[i];}
   delete [] q;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误消息更改为:

 main.cpp:26: error: no matching function for call to ‘myMap(int (*)(int), int*&, int)’
Run Code Online (Sandbox Code Playgroud)

这可能是非常错误的,但我无法找到.

编辑:错误:1)我错误输入指向函数的指针.它是X(*func)(X)而不是X*func(X).2)忘了分配temp.必须这样做X * temp = new X[size].3)还有错误吗?

Edw*_*nge 5

X * func(X)没有说出你的想法.你想要的X (*func)(X).