c – 检查是否将std :: function分配给nullptr

我想知道是否有任何方法来检查您分配到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

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

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

解决方法

这是你的std :: function实现中的一个错误(也很明显是我的),标准说运算符!如果对象是用null函数指针构造的,则返回true,参见[func.wrap.func]段落8.赋值运算符应该等同于用参数构造std :: function并交换它,所以运算符!在这种情况下也应该返回true.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...