Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an std::function is assigned to a nullptr

I am wondering if there is any way to check if a function pointer you assigned into an std::function was a nullptr. I was expecting the !-operator to do it, but it only seems to work when the function has been assigned something of type nullptr_t.

typedef int (* initModuleProc)(int);

initModuleProc pProc = nullptr;
std::function<int (int)> m_pInit;

m_pInit = pProc;
std::cout << !pProc << std::endl;   // True
std::cout << !m_pInit << std::endl; // False, even though it's clearly assigned a nullptr
m_pInit = nullptr;
std::cout << !m_pInit << std::endl; // True

I wrote this helper function to work around this for now.

template<typename T>
void AssignToFunction(std::function<T> &func, T* value)
{
    if (value == nullptr)
    {
        func = nullptr;
    }
    else
    {
        func = value;
    }
}
like image 834
Erik Welander Avatar asked Aug 05 '13 19:08

Erik Welander


1 Answers

That's a bug in your std::function implementation (and also apparently in mine), the standard says that operator! shall return true if the object is constructed with a null function pointer, see [func.wrap.func] paragraph 8. The assignment operator should be equivalent to constructing a std::function with the argument and swapping it, so operator! should also return true in that case.

like image 192
Jonathan Wakely Avatar answered Sep 27 '22 22:09

Jonathan Wakely