如何用单个参数包裹函数以接受多个参数
How to wrap a function with single argument to accept multiple arguments?
我想要一些可以使我做的代码:
// Dummy function foo
double foo(double a){return a+1;}
// Some wrapping here ... which generates (maybe a pointer to)
double Foo(double a, ...){return a+1;}
// i.e. ignore any other arguments, just accept
这主要是因为我有一个结构成员,它将存储一个指针以函数(通常为 double (*)(double, double)
),但是某种情况下它必须存储一个指向一单元函数的指针(而且我真的不想使用boost.variant.variant)。
edit :对不起,如果我没有清楚地说,但是应该(某种程度上像转换器一样)适用于同一类型的无限单函数。/p>
由于您处于需要double x double -> double
功能的特定情况下,因此可以包装foo
如下:
double foo_w(double a, double) { return foo(a); }
如果您对一个更通用的解决方案感兴趣,则可以在他的答案中查看variadic模板,以了解穆罕默德雷扎·帕纳希(Mohammadreza Panahi)的参数数量(及其各自类型)。但是,尽量不要过度解决问题。; - )
而不是功能指针,如果使用C 11,则可以使用std::function
存储函数:
double foo(double, double) {}
double Foo(double, ...) {} //You could also use a template for this one
//Note that the number of parameters of 'func' should be the maximum possible
//arguments of the functions you want to store (here: 1 vs 2)
std::function<double(double, double)> func;
func = foo; //Ok
func = Foo; //Ok
//Now you can call 'func'
func(1, 2); //if 'func' == 'Foo', ignores the 2
这是两个通用解决方案。
编译时间
这可以使用variadic模板来完成:
double func(double x)
{
return x + 1;
}
template<typename... Ts>
double wrappedFunc(double x, const Ts&...)
{
return f(x);
}
wrappedFunc()
可以使用任何类型的任何参数调用,只有第一个才能实际使用并传递给f()
:
wrappedFunc(5.0, "Hello!", false, -23); // returns 6.0
运行时间
据我了解您所做的编辑,您正在寻找一种在运行时执行此操作的方法。这是使用函数模板在C 14中这样做的一种方法,返回具有可变参数数量的lambda,该lambda调用原始函数,传递其第一个参数并忽略其余部分:
template<typename Func>
auto getVariadicWrapper(Func func)
{
return [func](auto argument, auto...) {return func(argument);};
}
此功能模板可用于以以下方式构造包装器函数:
// Assuming func() is the same as before
// Create a wrapper function, which passes its first param to func and ignores the rest.
auto wrappedFunc = getVariadicWrapper(func);
// Use it
wrappedFunc(5.0, false, "bananas", 72233); // returns 6.0
lambda
的另一种不错的方法是如果您有
double func (double a)
{
return a;
}
struct st
{
double(*foo)(double,double);
};
您可以做
st a;
a.foo = [](double a,double b){return func(a);};
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- Cython包裹CPP结构并用参数构成结构的阵列
- 什么是包裹着色器参数值的类的好设计模式
- 如何用单个参数包裹函数以接受多个参数
- 将参数一个接一个地传递,或通过将它们包裹在数组,结构或元组中