我想知道是否有任何方法来检查你分配到一个函数指针是否std::function是一个nullptr.我期待!-operator能够做到这一点,但它似乎只在函数被分配了类型的东西时起作用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
Run Code Online (Sandbox Code Playgroud)
我写了这个辅助函数来解决这个问题.
template<typename T>
void AssignToFunction(std::function<T> &func, T* value)
{
if (value == nullptr)
{
func = nullptr;
}
else
{
func = value;
}
}
Run Code Online (Sandbox Code Playgroud)