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