Skip to content

How to test if a member std::function is empty, and how to reset it to nullptr? #321

@totalgee

Description

@totalgee

This is a question not addressed in the cheatsheet, as far as I can tell... I asked a question two weeks ago on the forum, but haven't seen any responses there -- sorry for the repeat posting.

I have a C++ class member that holds a callback function pointer. It is a std::function, so it's valid for it to be empty (nullptr). I have no problems binding the class in ChaiScript, but I don't know the proper way to test if that member is empty, nor how to set it to nullptr (or 0).

// Example struct with callback member
struct MyClass {
    std::function<float(float)> callbackFunc = {};
};

// After registering MyClass, register the member:
m->add(fun(&MyClass::callbackFunc), "callbackFunc");

In scripting, I am able to create an instance of my class, assign a lambda function to it, and evaluate the function (e.g. using obj.callbackFunc(3.1f)). But I don't know how to check if it's empty, or how to reset it to nullptr (or 0). For the empty (boolean) test, I tried adding a type conversion:

chai.add(type_conversion<decltype(MyClass::callbackFunc), bool>([](decltype(MyClass::callbackFunc) f) { return f != nullptr; }));

That doesn't work, I get a "Condition not boolean" when trying to test the member. For the assignment, I tried various permutations of operator= (taking an int argument, i.e. 0), but haven't yet hit on something that worked.

I can make a specific method to check or reset that member, but I'd rather something that worked "automatically" for any type of std::function variable.

For the emptiness test, I came across this in the docs:

obj.callbackFunc.is_var_null()

but that doesn't seem to work (it returns false whether or not my callbackFunc is set to something), presumably because std::function is an object and not (directly) a pointer...

Any suggestions?

Desired Behaviour

obj = MyClass();
obj.callbackFunc = fun(x) { return x * 13.5f; }; // callbackFunc is a std::function member defined in C++

if (!obj.callbackFunc) {
    print("callback not set");
}
else {
    print(obj.callbackFunc(3.1f));
}
obj.callbackFunc = nullptr; // or "obj.callbackFunc = 0" would be fine

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions