A Container for Pointers to Functions

Many times, you’ll find you need to create a container for pointers to functions. The example below demonstrates the syntax for a vector of pointers to functions. For simplicity’s sake, only one function, is_positive(double), has been defined. Notice how the vector of pointers to functions is declared, how the next pointer is added to the vector, and how an element of the vector is invoked using an iterator. The benefit of this technique is twofold: utilizing the power of the STL containers and the flexibility of pointers to functions.

bool is_positive(double a){ return a > 0.0;}#include #include int main(){    std::vector fp;// declaration    for( long i = 0; i < 10; ++i )        fp.push_back(&is_positive);// adding    std::vector::iterator it;    double a = -4.0;    for( it = fp.begin(); it != fp.end(); ++it )             std::cout <<(*it)(a++)<< " ";//invocation    std::cout << std::endl;    return 0;}// the program output is "0 0 0 0 0 1 1 1 1 1"
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: