Pergunta

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;
    }
}
Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top