-
Free Functions: You can pass a pointer to a function that matches the expected signature.
void my_function() {
// Task implementation
}
boost::asio::io_context io_context;
boost::asio::post(io_context, my_function);
-
Lambda Expressions: You can use lambdas, which can capture local variables or state.
int value = 42;
boost::asio::io_context io_context;
boost::asio::post(io_context, [value]() {
std::cout << "Value: " << value << std::endl;
});
-
Function Objects (Functors): You can pass instances of functor classes.
struct MyFunctor {
void operator()() const {
std::cout << "Executing functor." << std::endl;
}
};
boost::asio::io_context io_context;
boost::asio::post(io_context, MyFunctor());
-
Member Functions: If you want to call a member function, you'll need to bind it to an instance of the class.
struct MyClass {
void my_member_function() {
std::cout << "Executing member function." << std::endl;
}
};
boost::asio::io_context io_context;
MyClass obj;
boost::asio::post(io_context, std::bind(&MyClass::my_member_function, &obj));
-
std::function: You can use std::function to encapsulate any callable type.
std::function<void()> task = []() {
std::cout << "Running from std::function." << std::endl;
};
boost::asio::io_context io_context;
boost::asio::post(io_context, task);
-
Using std::bind: This allows you to bind the parameters of a function to specific values.
void my_function_with_params(int x) {
std::cout << "Value: " << x << std::endl;
}
boost::asio::io_context io_context;
boost::asio::post(io_context, std::bind(my_function_with_params, 10));
-
C++17 std::any, std::variant, or other types: If you're using C++17 or later, you can pass wrappers around coroutines or tasks that you plan to run.
boost::asio::io_context io_context;
boost::asio::post(io_context, []() {
// Some complex task
});