c – Lambda作为类成员

前端之家收集整理的这篇文章主要介绍了c – Lambda作为类成员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有可能接受两种不同类型的lambda函数作为类成员而不知道他们的模板参数提前?
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,double y){cout << x * y << endl;};
    multiply_and_divide.b = [a,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();
    }

}

解决方法

如果您只想在不同时间构造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();
    }
}
原文链接:https://www.f2er.com/c/119360.html

猜你在找的C&C++相关文章