如何将通用函数指针作为参数传递 [英] How to pass a generic function pointer as parameter

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

问题描述

我有几个具有相似声明的函数:

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);
}

fn就像一个通用函数指针,可以接受foobartest

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

这可能吗?

顺便说一句,目前我的项目中没有C ++ 11,仅使用TR1就可以增强它.

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

推荐答案

您可以使用模板

示例(不完全是您的代码):

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;
}

这将按预期输出:

2
5

您可以在此处实时查看它 http://ideone.com/q3FyI5

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

这篇关于如何将通用函数指针作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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