7

テンプレート引数を事前に知らなくても、 2 つの異なるタイプのラムダ関数をクラス メンバーとして受け入れることは可能ですか?

struct two_functors {
    std::function<???> a;
    std::function<???> b;
    ...
};

このようなことが可能になるように:

void main(){
    vector<two_functors> many_functors;

    int a = 2;
    int b = 3;
    double c = 4.7;
    double d = 8.4;

    two_functors add_and_subtract;
    add_and_subtract.a = [a, b](int x, int y){cout << x + y << endl;};
    add_and_subtract.b = [c, d](double x, double y){cout << x - y << endl;};

    two_functors multiply_and_divide;
    multiply_and_divide.a = [c, d](double x, double y){cout << x * y << endl;};
    multiply_and_divide.b = [a, b](int x, int y){cout << x / y << endl;};

    many_functors.push_back(add_and_subtract);
    many_functors.push_back(multiply_and_divide);

    for (auto functors : many_functors){
        functors.a();
        functors.b();
    }

}
4

4 に答える 4

3

さまざまな時点で構築したいtwo_functorsが、後でそれらを一度に順番に実行したい場合は、キャプチャされたデータを使用できます。

struct two_functors
{
    function<void ()> a;
    function<void ()> b;
};

int main()
{
    vector<two_functors> many_functors;

    int a = 2;
    int b = 3;
    double c = 4.7;
    double d = 8.4;

    two_functors add_and_subtract {
        [a, b](){cout << a + b << endl;},
        [c, d](){cout << c - d << endl;}
    };

    two_functors multiply_and_divide {
        [c, d](){cout << c * d << endl;},
        [a, b](){cout << a / b << endl;}
    };

    many_functors.push_back(add_and_subtract);
    many_functors.push_back(multiply_and_divide);

    for (auto functors : many_functors){
        functors.a();
        functors.b();
    }
}
于 2013-06-05T18:15:54.397 に答える
0

スティーブンの答えに代わるものは、中間の「傘」クラスを使用することです。

編集:g ++(GCC)4.5.3で例をコンパイルしました

 #include <functional>
 #include <iostream>

 using namespace std;

 class myfunction
 {

 };

 template <typename T>
 class specificFunction : public myfunction
 {
     public:
     function<T> f;

     specificFunction(function<T> pf)
     {
         f = pf;
     }
 };

 struct two_functors {
     myfunction* a;
     myfunction* b;
 };



int main()
{
     myfunction* f = new specificFunction<void(int,int)> ([](int a, int b) { cout << a << " - " << b << endl; });
     myfunction* f2 = new specificFunction<void(double,int)> ([](double a, int b) { cout << a << " - " << b << endl; });

     two_functors tf;
     tf.a = f;
     tf.b = f2;

     ((specificFunction<void(int,int)>*)(tf.a))->f(4,5);
     ((specificFunction<void(double,int)>*)(tf.b))->f(4.02,5);

 }
于 2013-06-05T17:02:48.067 に答える
0

答えようとするのではなく (書式設定が必要なだけです)、スティーブンの提案のバリエーションにすぎません

template<typename A, typename B> 
two_functors<A,B> make_two_functors(A&& a, B&& b) {
   return two_functors<A,B> {a, b};
}

を使用する場合と比較して、欠点はありますstd::forward<T>か?

ところで、そのような「作成者」の必要性がC++ 11で消えてしまったらいいのにと思います。

于 2013-06-05T17:49:38.150 に答える