2010-11-29 33 views
3

我試圖在C++中學習模板,我嘗試的其中一件事是編寫一個像函數式語言中常見的映射函數。當時的想法是這樣的:在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; 
    } 

但是當我嘗試用這個:

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; 
} 

我編譯時類型不匹配錯誤:我試圖改變

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

它到:

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; 
} 

錯誤一團糟年齡變化爲:

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

這可能是非常錯誤的東西,但我找不到在哪裏。

編輯:錯誤其中: 1)我打錯了指針功能。它是X(* func)(X)而不是X * func(X)。 2)忘記分配溫度。必須做X * temp = new X[size]。 3)有沒有更多的錯誤?

+3

你知道這個函數已經存在於標準庫中了吧? (叫`std :: transform`) – jalf 2010-11-29 17:27:44

+0

噢,我只是想學習如何做到這一點。 – 2010-11-29 17:31:13

+0

您沒有爲新創建的陣列分配任何內存。 – sepp2k 2010-11-29 17:35:31

回答

1

你只是在這裏得到函數指針的語法錯誤。你想說:

template <class X> 
X* myMap(X (* func)(X), X * array, int size) 
{ 
    ... 
} 

爲了使這一功能更通用,使用模板參數,而不是一個函數指針,所以你可以同時使用普通的函數指針 C++函數對象(仿函數)。

template <class X, class F> 
X* myMap(F func, X * array, int size) 
{ 
    ... 
} 
-2

您沒有調用模板化的MyMap函數,您試圖調用非模板化的MyMap函數。嘗試q =我的地圖(.....)

5

X * func(X)並未說出你的想法。你想要X (*func)(X)

1

你非常接近。只需在X(*func)(X)左右丟失角色。耦合其他語法錯誤,在這裏修復:

#include <iostream> 
using namespace std; 


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; 
    } 

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; 
}