如何用单个参数包裹函数以接受多个参数

How to wrap a function with single argument to accept multiple arguments?

本文关键字:参数 包裹 何用单 函数      更新时间:2023-10-16

我想要一些可以使我做的代码:

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