I am mainly a .NET programmer working on a C++ project and am trying to determine the equivalent way to handle delegates that use the Action and Function template types. I use the delegates both as events and callbacks within the .NET code. My C++ project uses smart pointers and the same delegate design patterns as a C# program would. What is the best way to handle this situation? It is not clear to me how to pass and maintain a function pointer that also keeps track of the smart pointer and potentially the deletion of the underlying object since the event container uses a weak reference. The library needs to be multi-platform so using CLR is unfortunately not an option.
问问题
1645 次
2 回答
1
您正在寻找的是绑定到现有对象的方法指针,就是这样吗?
你应该看看boost::bind。如果你的环境支持它,你也可以使用std::tr1::bind
或者即使std::bind
它支持 C++11。
说明您想要的示例是:
struct X
{
bool f(int a);
};
X x;
shared_ptr<X> p(new X);
int i = 5;
bind(&X::f, ref(x), _1)(i); // x.f(i)
bind(&X::f, &x, _1)(i); //(&x)->f(i)
bind(&X::f, x, _1)(i); // (internal copy of x).f(i)
bind(&X::f, p, _1)(i); // (internal copy of p)->f(i)
最后两个例子很有趣,因为它们产生了“自包含”的函数对象。bind(&X::f, x, _1) 存储 x 的副本。bind(&X::f, p, _1) 存储 p 的副本,由于 p 是 boost::shared_ptr,因此函数对象保留对其 X 实例的引用,即使 p 超出范围或是重置()。
对于和之间的区别boost::bind
,我让您在 SO 上看到另一个问题。std::tr1::bind
std::bind
于 2012-12-11T09:53:17.343 回答
0
看看: http: //www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible
它还将解释为什么 C++ 中的委托有点棘手。这个库是在我读过的游戏开发书中推荐的(所以我假设它非常快)。
于 2012-12-19T06:06:30.353 回答