Rafael S. Calsaverini
Rafael S. Calsaverini

Reputation: 14012

Map function in C++ with templates

I'm trying to learn templates in C++ and one of the things I was trying was to code a map function like the ones you typically find in functional languages. The idea was something like this:

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

But when I try to use this in:

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

I got a type mismatch error when compiling:

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

I tried to change it to:

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

The error message changes to:

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

This is probably something very wrong, but I can't find where.

EDIT: The errors where: 1) I mistyped the pointer to function. It's X (*func)(X) instead of X * func(X) . 2) forgot to allocate temp. Must do X * temp = new X[size]. 3) are there any more errors?

Upvotes: 3

Views: 2452

Answers (4)

Charles Salvia
Charles Salvia

Reputation: 53289

You're just getting the syntax for a function pointer wrong here. You want to say:

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

To make this function more generic, use a template parameter instead of a function pointer so you can use both plain function pointers and C++ function objects (functors).

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

Upvotes: 1

John Dibling
John Dibling

Reputation: 101456

You were very close. Just missing parens around X(*func)(X). Couple other syntax errors, fixed here:

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

Upvotes: 1

Edward Strange
Edward Strange

Reputation: 40849

X * func(X) does not say what you think it says. You want X (*func)(X).

Upvotes: 5

BobL
BobL

Reputation: 31

You're not calling your templated MyMap function, you'reattempting to call a non-templated MyMap function. Try q= MyMap(.....)

Upvotes: -2

Related Questions