2

我想在特定情况下使用函数指针。我正在使用foo具有以下原型的函数

foo(double (*func)(double,double));

我可以打电话foo给正常的方式:

double bar(double x, double y) {
    //stuff
};

int main(void) {
    foo(bar);
    return 0; 
};

但我想冻结 的值x以获得等效于double (*func)(double)这样的函数:

foo(bar(x,double))

C++ 中是否存在类似的语法?

4

2 回答 2

2

如果您不想使用std::bind/ ,这里有两种选择std::function

假设您的编译器支持将无状态 lambda 转换为函数指针,您可以使用 lambda 进行绑定x

void foo(double (*f)(double, double)) { (*f)(3.14159, 2.71828); }

double bar(double x, double y) { return x * y; };

int main()
{
    foo([](double x, double y) -> double { return bar(1.0, y); });
    return 0;
}

或者您甚至可以更改foo为接受任意函数对象的模板。这样您就可以使用具有捕获的 lambda:

template<typename TFunc>
void foo(TFunc f) { f(3.14159, 2.71828); }

double bar(double x, double y) { return x * y; };

int main()
{
    double fixedprm = 1.0;
    foo([fixedprm](double x, double y) -> double { return bar(fixedprm, y); });
    return 0;
}
于 2012-05-04T00:33:06.317 回答
1

std::bind如果你有 C++11,你可以使用。考虑以下示例,该示例通过在一次快速移动中将每个元素添加 5 来转换向量:

#include <iostream>
using std::cout;

#include <functional>
using std::plus;
using std::bind;
using std::placeholders::_1;

#include <vector>
using std::vector;

#include <algorithm>
using std::transform;

int main()
{
    vector<int> v {1, 3, 6};

    //here we bind the value 5 to the first argument of std::plus<int>()
    transform (v.begin(), v.end(), v.begin(), bind (plus<int>(), _1, 5));

    for (int i : v)
        cout << i << ' '; //outputs "6 8 11"
}

至于你的例子,我可以像这样写一些接近它的东西:

#include <iostream>
using std::cout;

#include <functional>
using std::bind;
using std::function;
using std::placeholders::_1;

void foo (function<double (double, double)> func) //take function object
{
    //try to multiply by 3, but will do 2 instead
    for (double i = 1.1; i < 5.6; i += 1.1)
        cout << func (i, 3) << ' '; 
}

double bar (double x, double y)
{
    return x * y;
}

int main()
{
    foo (bind (bar, _1, 2));
}

输出:

2.2 4.4 6.6 8.8 11

不过,我可能把事情复杂化了。这实际上是我第一次同时使用std::bindstd::function

于 2012-05-03T23:19:18.000 回答