- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有一个 KeyCallback
vector :
typedef boost::function<void (const KeyEvent&)> KeyCallback
我用它来存储按下键盘按钮时的所有监听器。我可以使用 for_each
添加它们并将事件分派(dispatch)给所有回调,但我不知道如何从我的 vector 中实际删除特定的 KeyCallback
签名。
例如我想要这样的东西:
void InputManager::UnregisterCallback(KeyCallback callback) {
mKeyCallbacks.erase(std::find(mKeyCallbacks.begin(), mKeyCallbacks.end(), callback));
}
根据 boost::function
文档(参见 here ),没有比较函数对象这样的东西,这可以解释我的上述问题。那我卡住了吗?有什么好的解决方法吗?
(我阅读了有关回调机制的 boost::signals
,但它显然很慢,我预计回调可能会在一帧中触发多次。)
最佳答案
http://www.boost.org/doc/libs/1_51_0/doc/html/function/tutorial.html#id1546064
Function object wrappers can be compared via == or != against any function object that can be stored within the wrapper.
因此,解决方案之一是为 UnregisterCallback 的参数定义特殊类型(也支持类型删除)。这是基于事实,你可以将 boost::function 与仿函数/函数进行比较——结果你仍然会有 boost::function 的 vector ,只有在你需要执行比较的地方才需要新类型,例如取消注册回调:
#include <boost/scoped_ptr.hpp>
#include <boost/function.hpp>
#include <algorithm>
#include <iostream>
#include <typeinfo>
#include <ostream>
#include <vector>
#include <string>
using namespace std;
using namespace boost;
typedef int KeyEvent;
typedef function<void (const KeyEvent &)> KeyCallback;
struct AbstractCallback
{
virtual bool equals(const KeyCallback &f) const=0;
virtual ~AbstractCallback(){}
};
template<typename Callback>
struct ConcreteCallback : AbstractCallback
{
const Callback &callback;
explicit ConcreteCallback(const Callback &p_callback) : callback(p_callback) {}
virtual bool equals(const KeyCallback &f) const
{
return callback == f;
}
};
struct KeyCallbackChecker
{
scoped_ptr<AbstractCallback> func;
public:
template<typename Func>
KeyCallbackChecker(const Func &f) : func(new ConcreteCallback<Func>(f)) {}
friend bool operator==(const KeyCallback &lhs,const KeyCallbackChecker &rhs)
{
return rhs.func->equals(lhs);
}
friend bool operator==(const KeyCallbackChecker &lhs,const KeyCallback &rhs)
{
return rhs==lhs;
}
};
void func1(const KeyEvent &)
{
cout << "func1" << endl;
}
void func3(const KeyEvent &)
{
cout << "func3" << endl;
}
class func2
{
int data;
public:
explicit func2(int n) : data(n) {}
friend bool operator==(const func2 &lhs,const func2 &rhs)
{
return lhs.data==rhs.data;
}
void operator()(const KeyEvent &)
{
cout << "func2, data=" << data << endl;
}
};
struct Caller
{
template<typename F> void operator()(F f)
{
f(1);
}
};
class Callbacks
{
vector<KeyCallback> v;
public:
void register_callback(const KeyCallback &callback)
{
v.push_back(callback);
}
void unregister_callback(const KeyCallbackChecker &callback)
{
vector<KeyCallback>::iterator it=find(v.begin(),v.end(),callback);
if(it!=v.end())
v.erase(it);
}
void call_all()
{
for_each(v.begin(),v.end(),Caller());
cout << string(16,'_') << endl;
}
};
int main(int argc,char *argv[])
{
Callbacks cb;
cb.register_callback(func1);
cb.register_callback(func2(1));
cb.register_callback(func2(2));
cb.register_callback(func3);
cb.call_all();
cb.unregister_callback(func2(2));
cb.call_all();
cb.unregister_callback(func1);
cb.call_all();
return 0;
}
输出是:
func1
func2, data=1
func2, data=2
func3
________________
func1
func2, data=1
func3
________________
func2, data=1
func3
________________
优点:
缺点:
另一种方法是实现自定义的 boost::function-like 解决方案,它只接受可比较的回调。
#include <boost/shared_ptr.hpp>
#include <algorithm>
#include <iostream>
#include <typeinfo>
#include <ostream>
#include <vector>
using namespace std;
using namespace boost;
typedef int KeyEvent;
typedef void (*func_type)(const KeyEvent &);
struct AbstractCallback
{
virtual void operator()(const KeyEvent &p)=0;
virtual bool compare_to(const std::type_info &rhs_type,const void *rhs) const=0;
virtual bool compare_to(const std::type_info &rhs_type,const func_type *rhs) const=0;
virtual bool equals(const AbstractCallback &rhs) const=0;
};
template<typename Callback>
struct ConcreteCallback : AbstractCallback
{
Callback callback;
ConcreteCallback(Callback p_callback) : callback(p_callback) {}
void operator()(const KeyEvent &p)
{
callback(p);
}
bool compare_to(const std::type_info &rhs_type,const void *rhs) const
{
return (typeid(Callback)==rhs_type) &&
( *static_cast<const Callback*>(rhs) == callback );
}
bool compare_to(const std::type_info &rhs_type,const func_type *rhs) const
{
return false;
}
bool equals(const AbstractCallback &rhs) const
{
return rhs.compare_to(typeid(Callback),&callback);
}
};
template<>
struct ConcreteCallback<func_type> : AbstractCallback
{
func_type callback;
ConcreteCallback(func_type p_callback) : callback(p_callback) {}
void operator()(const KeyEvent &p)
{
callback(p);
}
bool compare_to(const std::type_info &rhs_type,const void *rhs) const
{
return false;
}
bool compare_to(const std::type_info &rhs_type,const func_type *rhs) const
{
return *rhs == callback;
}
bool equals(const AbstractCallback &rhs) const
{
return rhs.compare_to(typeid(func_type),&callback);
}
};
struct KeyCallback
{
shared_ptr<AbstractCallback> func;
public:
template<typename Func>
KeyCallback(Func f) : func(new ConcreteCallback<Func>(f)) {}
friend bool operator==(const KeyCallback &lhs,const KeyCallback &rhs)
{
return lhs.func->equals(*rhs.func);
}
void operator()(const KeyEvent &p)
{
(*func)(p);
}
};
void func1(const KeyEvent &)
{
cout << "func1" << endl;
}
void func3(const KeyEvent &)
{
cout << "func3" << endl;
}
class func2
{
int data;
public:
func2(int n) : data(n) {}
friend bool operator==(const func2 &lhs,const func2 &rhs)
{
return lhs.data==rhs.data;
}
void operator()(const KeyEvent &)
{
cout << "func2, data=" << data << endl;
}
};
struct Caller
{
template<typename F>
void operator()(F f)
{
f(1);
}
};
int main(int argc,char *argv[])
{
vector<KeyCallback> v;
v.push_back(KeyCallback(func1));
v.push_back(KeyCallback(func1));
v.push_back(KeyCallback(func1));
v.push_back(KeyCallback(func2(1)));
v.push_back(KeyCallback(func2(1)));
v.push_back(KeyCallback(func2(2)));
v.push_back(KeyCallback(func2(2)));
v.push_back(KeyCallback(func2(2)));
v.push_back(KeyCallback(func2(2)));
v.push_back(KeyCallback(func3));
for_each(v.begin(),v.end(),Caller());
cout << count(v.begin(),v.end(),KeyCallback(func1)) << endl;
cout << count(v.begin(),v.end(),KeyCallback(func2(1))) << endl;
cout << count(v.begin(),v.end(),KeyCallback(func2(2))) << endl;
cout << count(v.begin(),v.end(),KeyCallback(func3)) << endl;
return 0;
}
输出是:
func1
func1
func1
func2, data=1
func2, data=1
func2, data=2
func2, data=2
func2, data=2
func2, data=2
func3
3
2
4
1
优点:
缺点:
这里我们正在创建继承自 std/boost::function 的新类
#include <type_traits>
#include <functional>
#include <algorithm>
#include <stdexcept>
#include <iostream>
#include <typeinfo>
#include <utility>
#include <ostream>
#include <vector>
#include <string>
using namespace std;
// _____________________________Implementation__________________________________________
#define USE_VARIADIC_TEMPLATES 0
template<typename Callback,typename Function>
bool func_compare(const Function &lhs,const Function &rhs)
{
typedef typename conditional<is_function<Callback>::value,typename add_pointer<Callback>::type,Callback>::type request_type;
if (const request_type* lhs_internal = lhs.template target<request_type>())
if (const request_type* rhs_internal = rhs.template target<request_type>())
return *rhs_internal == *lhs_internal;
return false;
}
#if USE_VARIADIC_TEMPLATES
#define FUNC_SIG_TYPES typename ...Args
#define FUNC_SIG_TYPES_PASS Args...
#else
#define FUNC_SIG_TYPES typename function_signature
#define FUNC_SIG_TYPES_PASS function_signature
#endif
template<FUNC_SIG_TYPES>
struct function_comparable: function<FUNC_SIG_TYPES_PASS>
{
typedef function<FUNC_SIG_TYPES_PASS> Function;
bool (*type_holder)(const Function &,const Function &);
public:
function_comparable(){}
template<typename Func>
function_comparable(Func f_)
: Function(f_), type_holder(func_compare<Func,Function>)
{
}
template<typename Func>
function_comparable &operator=(Func f_)
{
Function::operator=(f_);
type_holder=func_compare<Func,Function>;
return *this;
}
friend bool operator==(const Function &lhs,const function_comparable &rhs)
{
return rhs.type_holder(lhs,rhs);
}
friend bool operator==(const function_comparable &lhs,const Function &rhs)
{
return rhs==lhs;
}
friend void swap(function_comparable &lhs,function_comparable &rhs)// noexcept
{
lhs.swap(rhs);
lhs.type_holder.swap(rhs.type_holder);
}
};
// ________________________________Example______________________________________________
typedef void (function_signature)();
void func1()
{
cout << "func1" << endl;
}
void func3()
{
cout << "func3" << endl;
}
class func2
{
int data;
public:
explicit func2(int n) : data(n) {}
friend bool operator==(const func2 &lhs,const func2 &rhs)
{
return lhs.data==rhs.data;
}
void operator()()
{
cout << "func2, data=" << data << endl;
}
};
struct Caller
{
template<typename Func>
void operator()(Func f)
{
f();
}
};
class Callbacks
{
vector<function<function_signature>> v;
public:
void register_callback_comparator(function_comparable<function_signature> callback)
{
v.push_back(callback);
}
void register_callback(function<function_signature> callback)
{
v.push_back(callback);
}
void unregister_callback(function_comparable<function_signature> callback)
{
auto it=find(v.begin(),v.end(),callback);
if(it!=v.end())
v.erase(it);
else
throw runtime_error("not found");
}
void call_all()
{
for_each(v.begin(),v.end(),Caller());
cout << string(16,'_') << endl;
}
};
int main()
{
Callbacks cb;
function_comparable<function_signature> f;
f=func1;
cb.register_callback_comparator(f);
cb.register_callback(func2(1));
cb.register_callback(func2(2));
cb.register_callback(func3);
cb.call_all();
cb.unregister_callback(func2(2));
cb.call_all();
cb.unregister_callback(func1);
cb.call_all();
}
输出是:
func1
func2, data=1
func2, data=2
func3
________________
func1
func2, data=1
func3
________________
func2, data=1
func3
________________
优点:
缺点:
编辑:
Awesome, I'm trying it out #1 right now, but I do not quite understand why it works when we apply our own == operators?
boost::功能can be compared针对函数或仿函数,但不针对另一个 boost::function:
#include <boost/function.hpp>
void f1(){}
void f2(){}
int main()
{
boost::function<void ()> bf1(f1),bf2(f2);
bf1 == f1; // Works OK
//bf1 == bf2; - COMPILE ERROR
return 0;
}
在我们的 #1 方法中,我们进行类似于“bf1 == f1;”的比较。 KeyCallbackChecker 捕获仿函数/函数并在 ConcreteCallback::equals 中执行此类比较。
关于c++ - 在容器中存储 boost::function 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13094720/
我的一位教授给了我们一些考试练习题,其中一个问题类似于下面(伪代码): a.setColor(blue); b.setColor(red); a = b; b.setColor(purple); b
我似乎经常使用这个测试 if( object && object !== "null" && object !== "undefined" ){ doSomething(); } 在对象上,我
C# Object/object 是值类型还是引用类型? 我检查过它们可以保留引用,但是这个引用不能用于更改对象。 using System; class MyClass { public s
我在通过 AJAX 发送 json 时遇到问题。 var data = [{"name": "Will", "surname": "Smith", "age": "40"},{"name": "Wil
当我尝试访问我的 View 中的对象 {{result}} 时(我从 Express js 服务器发送该对象),它只显示 [object][object]有谁知道如何获取 JSON 格式的值吗? 这是
我有不同类型的数据(可能是字符串、整数......)。这是一个简单的例子: public static void main(String[] args) { before("one"); }
嗨,我是 json 和 javascript 的新手。 我在这个网站找到了使用json数据作为表格的方法。 我很好奇为什么当我尝试使用 json 数据作为表时,我得到 [Object,Object]
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我听别人说 null == object 比 object == null check 例如: void m1(Object obj ) { if(null == obj) // Is thi
Match 对象 提供了对正则表达式匹配的只读属性的访问。 说明 Match 对象只能通过 RegExp 对象的 Execute 方法来创建,该方法实际上返回了 Match 对象的集合。所有的
Class 对象 使用 Class 语句创建的对象。提供了对类的各种事件的访问。 说明 不允许显式地将一个变量声明为 Class 类型。在 VBScript 的上下文中,“类对象”一词指的是用
Folder 对象 提供对文件夹所有属性的访问。 说明 以下代码举例说明如何获得 Folder 对象并查看它的属性: Function ShowDateCreated(f
File 对象 提供对文件的所有属性的访问。 说明 以下代码举例说明如何获得一个 File 对象并查看它的属性: Function ShowDateCreated(fil
Drive 对象 提供对磁盘驱动器或网络共享的属性的访问。 说明 以下代码举例说明如何使用 Drive 对象访问驱动器的属性: Function ShowFreeSpac
FileSystemObject 对象 提供对计算机文件系统的访问。 说明 以下代码举例说明如何使用 FileSystemObject 对象返回一个 TextStream 对象,此对象可以被读
我是 javascript OOP 的新手,我认为这是一个相对基本的问题,但我无法通过搜索网络找到任何帮助。我是否遗漏了什么,或者我只是以错误的方式解决了这个问题? 这是我的示例代码: functio
我可以很容易地创造出很多不同的对象。例如像这样: var myObject = { myFunction: function () { return ""; } };
function Person(fname, lname) { this.fname = fname, this.lname = lname, this.getName = function()
任何人都可以向我解释为什么下面的代码给出 (object, Object) 吗? (console.log(dope) 给出了它应该的内容,但在 JSON.stringify 和 JSON.parse
我正在尝试完成散点图 exercise来自免费代码营。然而,我现在只自己学习了 d3 几个小时,在遵循 lynda.com 的教程后,我一直在尝试确定如何在工具提示中显示特定数据。 This code
我是一名优秀的程序员,十分优秀!