i am new to c++ programming and need help. The following code is an short example of the problem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
class A {
public:
std::string f(int i) {
return g(i);
}
private:
std::string g(int i) {
return"A.g " + std::to_string(i);
}
};
int main() {
A a;
std::cout << a.f(1) << std::endl;
}
Given is a class A and the class has a member function names g. The function g is used in another member function f. I want to modify the class such that I can swap the function g with an arbitrary other function.
My idea was to create a pointer p which points to the function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class A {
public:
using fct_type = std::string (int);
A(fct_type *custom)
: p(custom)
{}
std::string f(int i) {
return p(i);
}
private:
// ...
fct_type *p;
};
int main() {
A a([](int) { return std::string("arg"); });
std::cout << a.f(1) << std::endl;
}
This code still compiles and does what it should do. My problem is to set a default argument for the constructor:
1 2 3
A(fct_type *custom = &A::g)
: p(custom)
{}
The type of the default argument is std::string (A::*)(int) and not std::string (*)(int).
My question is how can I convert to type or is there another way of solving my problem? (Furthermore is efficiency a requirement. The function f is called often.)
Thank you very much. I already found std::bind but I did not know about std::function.
Also thank you for the small example which makes it easier to understand.