6

我想知道是否有任何方法可以检查您分配给 an 的函数指针是否std::functionnullptr. 我期待!-operator 这样做,但它似乎只在函数被分配了 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

我写了这个辅助函数来解决这个问题。

template<typename T>
void AssignToFunction(std::function<T> &func, T* value)
{
    if (value == nullptr)
    {
        func = nullptr;
    }
    else
    {
        func = value;
    }
}
4

1 回答 1

8

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.

于 2013-08-05T19:26:23.883 回答