Ask Your Question
0

What is the process for creating a container in c++ that is capable of accommodating functions of any type?

asked 2022-09-04 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-12-24 17:00:00 +0000

lalupa gravatar image

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!".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-04 11:00:00 +0000

Seen: 8 times

Last updated: Dec 24 '22