Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a container in C++ that can accommodate functions of any type, you can use templates. Here is a simple example:

#include <iostream>
#include <vector>

template <typename Func>
class FunctionContainer {
public:
    void add(Func f) {
        functions.push_back(f);
    }

    void run() {
        for (auto f : functions) {
            f();
        }
    }

private:
    std::vector<Func> functions;
};

void print_hello() {
    std::cout << "Hello, ";
}

void print_world() {
    std::cout << "world!\n";
}

int main() {
    FunctionContainer<void(*)()> container;
    container.add(print_hello);
    container.add(print_world);
    container.run();
    return 0;
}

In this example, a class FunctionContainer is defined that takes a template parameter Func. The add method can take any function with the same signature as Func and adds it to a vector of functions. The run method then loops through each function and calls it.

To use FunctionContainer, you simply need to create an instance with the appropriate template parameter, add the desired functions using the add method, and then call run. In this example, we create an instance with void(*)(), which represents a function that takes no arguments and returns void, and then add the print_hello and print_world functions. When we call run, it outputs "Hello, world!".