具有函数作为模板参数的C ++函数调用包装器 [英] C++ function call wrapper with function as template argument
问题描述
我正在尝试创建一个通用包装函数,该函数将一个函数作为模板参数,并将与该函数相同的参数作为其参数。例如:
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?
针对前两个回答,我将问题编辑为明确说明我需要能够在包装函数中进行工作(即在调用包装函数之前和之后修改一些全局状态)
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屋!