-2

I am wondering if there is any way to create a function as a variable or change a class's function on the fly. Here are some examples to show what I mean

Java

Thread t = new Thread() {
    public void run() {
        //do something
    }
}

Javascript

var f = function() {
    //do something
}

I am aware that you can use a predefined function as a variable, but I'm looking to do this entirely in a function.

connor
  • 19
  • 1
  • 3

1 Answers1

2

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); }
};
AlexG
  • 1,091
  • 7
  • 15