c++ - 检查 std::function 是否分配给 nullptr

标签 c++ c++11 std std-function nullptr

我想知道是否有任何方法可以检查您分配给 std::function 的函数指针是否为 nullptr。我期待 ! 运算符来执行此操作,但它似乎仅在为函数分配了 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 实现中的一个错误(显然也是我的),标准规定 operator! 应该返回 true 如果对象是用一个空函数指针,参见 [func.wrap.func] 第 8 段。赋值运算符应该等同于用参数构造一个 std::function 并交换它,所以 operator! 在这种情况下也应该返回 true。

关于c++ - 检查 std::function 是否分配给 nullptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065981/

相关文章:

c++ - 在父窗口中限制可拖动的子窗口?

c++ - 为什么shared_ptr类型没有模板分配器参数?

c++ - 声明模板类型以调用 make_pair

c++11 - 从一种模板实例化转换为另一种模板实例化

C++ 列表 : copying a local list in a member list

c++ - 使用正态分布优化预期 yield

c++ - ARM GCC 堆未完全使用

c++ - 有没有办法像 C++ 中的 printf 那样用参数替换字符串?

c++ - std::function 是否具有用于复制和移动的虚函数?

c++ - std::all_of 不接受类成员函数作为具有 1 个参数的函数