1

i have a question regaring c++ and arrays.

let say i have a class which is called CustomArray, and is nothing more than an generic array wich has attributes for size and capacity, to make the array dynamic. defined as:

template<typename T>
class CustomArray
{
public:
    int capacity, size;
    T* items;
    //constructor

    //destructor

    //function1

    //function2

    //etc...
};

now i'm kinda stuck, i want to implement a function like:"

void performOnAllItems(/*function?*/)
{
    for(int i = 0; i < size; i++)
    {
        //perform function on element
    }
}

that takes another function as a parameter (if that is possible?) and performs it on all elements. is that possible? and if so... how?

thanks in advance.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
Marnix v. R.
  • 1,638
  • 4
  • 22
  • 33

3 Answers3

9

Add members begin and end like so:

T *begin() { return items; }

T *end() { return items + size; }

Create a functor that derives from std::unary_function.

E.g.

template <typename T>
class MyFunc : std::unary_function<T, void> {
public:
    void operator()(T& t) {
    // ...
    }
};

Then call std::foreach(foo.begin(), foo.end(), MyFunc);

Update

In C++11, you can use a lambda for the foreach:

std::foreach(foo.begin(), foo.end(),
              [/* (1) */](T& t) { /* ... */ }
            ); 

If (1) isn't empty, then the lambda is a closure; this is known as a capturing lambda, and Visual C++ 10 Lambda Expressions provides a nice example of this.

moshbear
  • 3,282
  • 1
  • 19
  • 33
6
template<class functionptr>
void performOnAllItems(functionptr ptr)
{
    for(int i = 0; i < size; i++)
        ptr(items[i]);
}

or

typedef void (*functionptr)(T&);
void performOnAllItems(functionptr ptr)
{
    for(int i = 0; i < size; i++)
        ptr(items[i]);
}

The second one greatly limits which functions can be used however, the first does not.

Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • 1
    I'll add that, as written, Mooing's first function should also work with functors (see [here](http://stackoverflow.com/questions/356950/c-functors-and-their-uses)) – Vlad Nov 16 '11 at 21:31
1

Sure. You just have to modify performOnAllItems to take a function pointer, which returns void and takes as a parameter either a T or pointer to T (per my solution below) that calls that function pointer for each item in the list.

template <typename T>
void CustomArray::performOnAllItems(void (*action)(T*))
{
    for(int i = 0; i < size; i++)
    {
        action(items + i);
    }
}
Adam Maras
  • 26,269
  • 6
  • 65
  • 91