I am trying to implement a class system that uses callbacks to notify of certain events. I can think of 2 ways to do this:
#include <functional>
#include <iostream>
class A {
public:
A(std::function<void(int)>&& func) : f(std::move(func)) {}
void run() { f(2); }
std::function<void(int)> f;
};
template <class F>
class B {
public:
B(F&& func) : f(std::move(func)) {}
void run() { f(2); }
F f;
};
int main() {
int n = 1;
A a1([n](int b){std::cout << n+b << '\n';});
B b1([n](int b){std::cout << n+b << '\n';});
a1.run();
b1.run();
}
What are the advantages/disadvantages of using these 2 approaches (having a template type for the callback type vs. using std::function)