Search code examples
c++c++11c++14std-function

How to check if a std::function is set and valid?


I have an std::function which is being set like below:

typedef std::function<void(bool some_state)> TheListener;
void ListenTo(TheListener the_listener) {
    m_the_listener = the_listener;
}

How do I check if the std::function is set?

private:
    void SomePrivateMethod() {
        // How do I check here that m_the_listener is set by calling ListenTo ?
        m_the_listener();
    }

Is it enough to check if (m_the_listener) before calling m_the_listener() ?


Solution

  • This does state that verifying the std::function instance in a condition should be sufficient to verify if it has a valid callable target. So yes, if (m_the_listener) should be enough.