开发者

using templates with function pointer arguments

I was wondering how to use a template with a function pointer as an 开发者_运维百科argument. For instance,

template<typename T> someFunction(T /*?*/) {}

where T is a function pointer (e.g. void (*)(int,int*,double) )

I want to use this to bypass the difference issue for function pointers of two functions such as:

void function(int,int);
void class::function(int,int);

So, if function pointers don't work, is there another way?

Edit: Basically, I need to make a function that accepts a variety of functions by using a template (just as a regular template function accepts a variety of variables).


Member function pointers are a different beast than function pointers, for instance there is an additional this argument for them. Its not entirely clear what you are trying to accomplish, sounds like Boost.Function/Bind would help. Note they are standard since TR1.


You may use functors instead of pointers to member functions. An example:

class SomeFunctor {
public:
    void operator()(int i, int* ip, double d)
    {
    }
};

void someFunction(int i, int* ip, double d)
{
}

template<typename T>
void doSomething(T f)
{
    int i = 0, j = 0;
    int* ip = &j;
    double d;

    f(i, ip, d);
}

SomeFunctor someFunctor;
doSomething(someFunctor);
doSomething(someFunction);

Note that I have not tested this code and therefore, some modifications may be needed to get it to compile.


You should look at std::function ; it's a generalized way of holding a "functor", which is something that you can call. ( See npclaudiu's response for an example of one kind of functor )

That being said, K-ballo is correct, a member function is different than a free function, because it requires an object. This is typically implemented by having a hidden parameter passed in; you can refer to it as "this".

So when you write void my_class::function(int,int);

The compiler really generates void my_class::function (my_class*,int,int);

You can use std::bind to associate data and functions - to create functors on the fly. The best tutorial that I know of is for Boost.Bind

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜