C ++传递方法指针作为模板参数 [英] C++ passing method pointer as template argument

查看:197
本文介绍了C ++传递方法指针作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的调用函数:

I have a caller function like this:

template<typename T, void (T::*method)()>
void CallMethod(T *object){
    (object->*method)(args);
}

并且这个功能完美:

void (*function)(A *) = &CallMethod<A, &A::method>;

此代码不会在第二行编译时出错:

this code does not compile with error on the second line:

void (A::*method)() = &A::method;
void (*function)(A *) = &CallMethod<A, method>;

有没有办法解决它?我需要CallMethod模板来获取一个存储在变量中的方法的常量指针。

Is there any way to fix it? I need the CallMethod template to take a constant pointer to a method that is stored in a variable.

推荐答案

确定你有一个API,它接受一个函数和一个指针,你需要提供它。我假设你必须总是提供一个A *指针?

At this point I have ascertained that you have an API that takes a function and a pointer and you need to supply it such. I assume that you must always supply it an A* pointer?

如果它是一个非常通用的回调,但必须是一个函数(不能是boost ::函数)并且必须是一个指针(可能是void *),那么你需要一个这样的函数:

If it is a very generic callback but must be a function (can't be a boost::function) and must be a pointer (possibly void*) then you need a function a bit like this:

struct GenericHolder
{
   boost::function0<void> func;
};

void GenericCallback( void * p )
{
   GenericHolder * holder = static_cast< GenericHolder * >(p);
   holder->func();
   delete holder;
}

在这种情况下,我在调用时调用delete,我们在调用时调用new,即当你建立你的指针,你的呼叫。当然,这可能不是你传递的指针在第一次调用时被删除,所以要适当地管理生命周期。

As in this case I am calling delete at call time, so I have assume we call new at invoke time, i.e. when you build up your pointer on which your call is made. Of course it might not be that your pointer you pass is deleted on first call, so manage the lifetime appropriately.

如果你在控制另一边不要通过设计来做,但让这一边持有boost ::函数,并调用它。

If you are in control of the "other side" then don't do this by design but let that side hold the boost::function and just call it.

内存管理仍然可能是一个问题,你需要照顾。例如,当你调用boost :: bind它在你的幕后的结构中包装东西。如果这些是你分配给新的指针,你需要在某个时候删除它们。如果它们是引用,它们必须在调用点处仍然有效。指向局部变量的指针也可能是一个问题。 shared_ptrs是理想的,当然。如果你使用这个概念,bug跟踪到boost :: bind错误是很难找到的。

Memory management can still be an issue you need to take care of. For example, when you call boost::bind it wraps things in a struct behind the scenes for you. If these are pointers you allocated with new you need to delete them at sometime. If they are references they must still be valid at the point of call. pointers to local variables can also be a problem. shared_ptrs are ideal, of course. And the bug tracking to the boost::bind error is very very hard to find if you use that concept a lot.

这篇关于C ++传递方法指针作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆