How to pass a generic function pointer as parameter

坚强是说给别人听的谎言 提交于 2019-12-07 14:47:32

问题


I have several functions that having similiar declarations:

int foo(int a);
int bar(int a);
int test(int a);

And the logics of my message handlers are exactly the same:

void HandleFoo(int a) {
    process(a);
    int ret = foo(a);
    if (ret) 
        print(a);
}

void HandleBar(int a) {
    process(a);
    int ret = bar(a);
    if (ret) 
        print(a);
}

void HandleTest(int a) {
    process(a);
    int ret = test(a);
    if (ret) 
        print(a);
}

So I am wondering if it is possible to write a general function:

void Handle(int a, func_pointer fn) {
    process(a);
    int ret = fn(a);
    if (ret) 
        print(a);
}

The fn is like a generic function pointer that can accept foo, bar and test

Is this possible?

Btw, currently no C++11 and boost in my project, only using TR1.


回答1:


You can use a template

Example (not your code exactly) :

int add1(int n) { return n+1; }
int add2(int n) { return n+2; }

template<typename Adder>
void AddHandler(int n, Adder adder)
{
    int r = adder(n);
    std::cout << r << std::endl;
}

int main(void)
{
    AddHandler(1, add1);
    AddHandler(3, add2);

    return 0;
}

This outputs as expected :

2
5

You can see it live here http://ideone.com/q3FyI5




回答2:


Convert the functions to functors, i.e.

struct foo
{
  int operator()(int a) {}
};
struct bar
{
  int operator()(int a) {}
};
struct test
{
  int operator()(int a) {}
};

then the previous approach works, with a slight tweak

template <typename Functor>
void Handle(int a)
{
  process(a);
  int ret = Functor()(a); // <- tweak, instantiate functor and then call
  if (ret) 
      print(a);
}

You can take this approach or @undu's where you pass the function to call as an argument...




回答3:


Yes it is. Use

void Handle(int a, int(*func)(int)) {
  process(a);
  int ret = (*func)(a);
}

Use like so:

Handle(some_a, &foo);

Note: the three functions you posted as example return void, I suspected a typo and replaced them with int.




回答4:


typedef int (*fptr)(int ) ;

void Handle(int a, fptr fn) {
    process(a);
    int ret = fn(a);
    if (ret) 
        print(a);
}

int main()
{
    Handle(3,foo);
    Handle(4,bar);
    Handle(5,test);
}



回答5:


Use

void Handle(int a, bool(*fn)(int) ) {
    process(a);
    int ret = fn(a);
    if (ret) 
        print(a);
}

Or,

typedef bool (*func_pointer)(int);
void Handle(int a, func_pointer fn ) {
    process(a);
    int ret = fn(a);
    if (ret) 
        print(a);
}


来源:https://stackoverflow.com/questions/17965057/how-to-pass-a-generic-function-pointer-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!