小编Eri*_*der的帖子

检查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
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)

c++ std nullptr c++11 std-function

6
推荐指数
1
解决办法
4154
查看次数

标签 统计

c++ ×1

c++11 ×1

nullptr ×1

std ×1

std-function ×1