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


Hi there, 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 how to be able 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.

Any tips? Thanks,


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


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


Anyone got any ideas on how to deal with nullness-testing for function objects in ChaiScript? And how to reset such a pointer to nullptr (without having to make a specific assignment operator for each type of function template implementation)?


Discussion on this topic has continued here: ChaiScript/ChaiScript#321.