具有函数作为模板参数的C ++函数调用包装器 [英] C++ function call wrapper with function as template argument

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

问题描述

我正在尝试创建一个通用包装函数,该函数将一个函数作为模板参数,并将与该函数相同的参数作为其参数。例如:

I'm trying to create a generic wrapper function that takes a function as a template argument and takes the same arguments as that function as its arguments. For example:

template <typename F, F func>
/* return type of F */ wrapper(Ts... Args /* not sure how to get Ts*/)
{
    // do stuff
    auto ret = F(std::forward<Ts>(args)...);
    // do some other stuff
    return ret;
}

解决方案必须可转换为与 func ,这样我可以将其传递给C api。换句话说,解决方案需要是一个函数而不是一个函数对象。最重要的是,我需要能够在包装函数中完成工作

The solution needs to be castable to a function pointer with the same type as func so that I can pass it to a C api. In other words, the solution needs to be a function and not a function object. Most importantly, I need to be able to do work in the wrapper function.

如果内嵌注释不清楚,我会希望能够执行以下操作:

If the inline comments aren't clear, I'd like to be able to do something like the following:

struct c_api_interface {
    int (*func_a)(int, int);
    int (*func_b)(char, char, char);
};

int foo(int a, int b)
{
    return a + b;
}

int bar(char a, char b, char c)
{
    return a + b * c;
}

c_api_interface my_interface;
my_interface.func_a = wrapper<foo>;
my_interface.func_b = wrapper<bar>;

我在寻找相关的帖子并找到了这些帖子,但是这些都不是我想要的做。这些帖子大多数涉及功能对象。我想做的事甚至有可能吗?

I looked for related posts and found these, but none of them are quite what I'm trying to do. Most of these posts concern function objects. Is what I'm trying to do even possible?

作为模板参数传递的函数

通过(功能对象)类(可变)模板的功能包装器

如何包装函数指针和函数对象

如何在可变参数模板类中获取函数指针的参数类型?

具有任何参数列表的函数的通用函子

C ++函子-及其用途

针对前两个回答,我将问题编辑为明确说明我需要能够在包装函数中进行工作(即在调用包装函数之前和之后修改一些全局状态)

In response to the first 2 responses, I edited the question to make it clear that I need to be able to do work in the wrapper function (i.e. modify some global state before and after the call to the wrapped function)

推荐答案

#include <utility>
#include <iostream>

struct c_api_interface { int (*func_a)(int, int); int (*func_b)(char, char, char); };
int foo(int a, int b) { return a + b; }
int bar(char a, char b, char c) { return a + b * c; }


template<typename Fn, Fn fn, typename... Args>
typename std::result_of<Fn(Args...)>::type
wrapper(Args... args) {
   std::cout << "and ....it's a wrap ";
   return fn(std::forward<Args>(args)...);
}
#define WRAPIT(FUNC) wrapper<decltype(&FUNC), &FUNC>

int main() {
  c_api_interface my_interface;
  my_interface.func_a = WRAPIT(foo);
  my_interface.func_b = WRAPIT(bar);

  std:: cout << my_interface.func_a(1,1) << std::endl;
  std:: cout << my_interface.func_b('a','b', 1) << std::endl;

  return 0;
}

请参见 http://rextester.com/ZZD18334

这篇关于具有函数作为模板参数的C ++函数调用包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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