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/を使用したくない場合は、次の 2 つの方法がありますstd::function

コンパイラがステートレス ラムダから関数ポインタへの変換をサポートしていると仮定すると、ラムダを使用してバインドできます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、任意の関数オブジェクトを受け入れるテンプレートに変更することもできます。そうすれば、キャプチャを持つラムダを使用できます。

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::bindC++11をお持ちの場合にご利用いただけます。1回の素早い動きで各要素に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::bindとの両方を使用するのは実際には初めてでしたstd::function

于 2012-05-03T23:19:18.000 に答える