与 2010 年相比,解决方案更新到 2012 年.std::function = 空错误
Updated vs 2010 solution to 2012. std::function = NULL error
我刚刚将 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);
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?