devxlogo

A Container for Pointers to Functions

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"
See also  Who are the Modern GPU Cloud Providers?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist