与 2010 年相比,解决方案更新到 2012 年.std::function = 空错误

Updated vs 2010 solution to 2012. std::function = NULL error

本文关键字:std function 错误 2012 更新 2010 解决方案      更新时间:2023-10-16

我刚刚将 2010 年的解决方案导入到 2012 年。

现在,当我编译程序(在2010年成功编译)失败并出现几个错误时,例如:

 c:usersfrizzlefrydocumentsvisual studio 2010projectsmenusystemmenusystemktext.cpp(288) : see reference to function template instantiation 'std::function<_Fty> &std::function<_Fty>::operator =<int>(_Fx &&)' being compiled
1>          with
1>          [
1>              _Fty=void (void),
1>              _Fx=int
1>          ]

转到 KText 中的第 288 行.cpp是这个函数:

void KText::OnKeyUp(SDLKey key, SDLMod mod, Uint16 unicode) {
    IsHeld.Time(500);       //Reset first repeat delay to 500 ms.
    IsHeld.Enable(false);   //Turn off timer to call the IsHeld.OnTime function.
    KeyFunc = NULL;     //LINE 288  //Set keyFunc to NULL 
}

我已经检查了其中的一些,它们都与将std::function<void()> func设置为NULL有关。

显然,我可以通过并更改buncha行,但是我的程序的设置方式可以检查:

if(func != NULL) func();

如何替换此类功能?

例如,

如果您看到std::function赋值运算符的引用,则实际上没有重载可以NULL任何东西(通常是在C++中定义为0的宏)。但您可以分配例如 nullptr到函数对象(根据引用中的重载 3):

KeyFunc = nullptr;

与比较相同,使用 nullptr 而不是 NULL .或者,正如 juanchopanza 在评论中建议的那样,使用 bool cast 运算符。

我更愿意让库决定function<>实例的默认构造值是什么:

KeyFunc = {}; // uniform initialization (c++11)
// or
KeyFunc = KeyFuncType(); // default construct

带有断言的演示:在 Coliru 上观看直播

#include <functional>
#include <cassert>
int main()
{
    using namespace std;
    function<int(void)> f = [] { return 42; };
    assert(f);
    assert(42 == f());
    f = nullptr;
    assert(!f);
    f = {};
    assert(!f);
}

如果您的编译器没有用于统一初始化的印章,请使用 typedef:

typedef function<int(void)> Func;
Func f = [] { return 42; };
assert(f);
f = Func();
assert(!f);