In the following source code, init_data_func()
is declared a friend function to the class Manger
.Therefore, whenever I want to pass a function as an argument to Manager::init_data(),
it must have the name 'init_data_func.'
How can I use an arbitrary name for the function and pass it as a parameter to Manager::init_data()?
#include <iostream>
class Manager {
private:
int n_;
int *a_, *b_, *c_;
public:
Manager(int n) : n_(n) {
a_ = new int[n];
b_ = new int[n];
c_ = new int[n];
}
~Manager() {
delete[] a_;
delete[] b_;
delete[] c_;
}
friend void init_data_func(Manager& manager);
void init_data(void (*init_data_func)(Manager&)) {
init_data_func(*this);
}
};
void init_data_func(Manager& manager) {
for (int i = 0; i < manager.n_; ++i) {
manager.a_[i] = rand();
manager.b_[i] = rand();
}
}
int main() {
const int N = 1000;
Manager manager(N);
// Initialize data using init_data_func
manager.init_data(&init_data_func);
return 0;
}