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!".
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
Asked: 2022-09-04 11:00:00 +0000
Seen: 8 times
Last updated: Dec 24 '22
What does an empty name signify in the inotify_event structure in the C++ language?
What is the method to get a printable output of a C++11 time_point?
What are the differences between TREEFROG, CROW, and the CPPCMS C++ framework?
How can the NTP flag be set for Linux time in C++?
What is the process of redefining a c++ macro with fewer parameters?
What are some other options instead of Scipy to compute CubicSpline?
How can a list be sorted alphabetically within a console application?