C++ is a compiled language. Therefore you cannot "change a class's function on the fly". Only interpreted languages can do that.
Here's a thing or two you CAN do in C++:
#include <functional> // For std::function
bool IsGreaterThan(int a, int b)
{
return a > b;
}
int main()
{
// 1. Create a lambda function that can be reused inside main()
const auto sum = [](int a, int b) { return a + b;};
int result = sum(4, 2); // result = 6
// 2. Use std::function to use a function as a variable
std::function<bool(int, int)> func = IsGreaterThan;
bool test = func(2, 1); // test = true because 2 > 1
}
In the second example, we've created a function pointer that takes into argument two int
and returns a bool
. The benefit of using std::function is that you can mix pointer to member functions with pointer to functions, as long as they have the same arguments and return values.
EDIT: Here's an example on how you would keep member and non member functions inside a single vector using std::function and std::bind.
bool IsGreaterThan(int a, int b)
{
return a > b;
}
typedef bool(*FunctionPointer)(int, int); // Typedef for a function pointer
// Some class
struct SomeClass
{
private:
vector<FunctionPointer> m_functionPointers;
vector<std::function<bool(int, int)>> m_stdFunctions;
public:
SomeClass()
{
// With regular function pointers
m_functionPointers.push_back(IsGreaterThan);
m_functionPointers.push_back(&this->DoSomething); // C2276: '&' : illegal operation on bound member function expression
// With std::function
m_stdFunctions.push_back(IsGreaterThan);
m_stdFunctions.push_back(std::bind(&SomeClass::DoSomething, this, std::placeholders::_1, std::placeholders::_2)); // Works just fine.
}
bool DoSomething(int a, int b) { return (a == b); }
};