std::bind函数作为函数、参数

    技术2022-07-10  125

    定义需要绑定参数的函数:

    #include <iostream> #include <vector> #include <functional> #include <cstring> using namespace std; // 占位符_1 、_2 所在的namespace using namespace std::placeholders; bool valid(const wstring &str, int nSize) { return str.size() > nSize ? true : false; } // 第二个参数是函数指针 bool verify(const wstring& str, function<bool(const wstring&, int)> compare) { return compare(str, 1); } //第二个参数是函数指针,第三个参数是输出参数 bool get_valid_string(const wstring& strVal, function<bool(const wstring&, int)> compare, wstring &strResult) { if (compare(strVal, 1)) { strResult = strVal; return true; } return false; }

    绑定参数、函数调用:

    wstring strVal(L"test"); //给函数valid绑定2个参数。第一个参数是占位符(必须与valid第一个参数类型等同),第二个是10 auto valid_func= bind(valid, _1, 10); // 调用函数对象valid_func bool bValid = valid_func(strVal); //false // 函数verify绑定的两个参数都是占位符。第一个是wstring类型,第二个是函数指针 auto verify_func = bind(verify, _1, _2); bool bPass = verify_func(strVal, valid); //true // 直接调用get_valid_string函数 wstring strResult; get_valid_string(strVal, valid, strResult); //strResult : "test" // 为get_valid_string绑定参数。三个参数分别为:wstring、函数指针、占位符 wstring strRet1; auto get_valid1 = bind(get_valid_string, strVal, valid, _3); get_valid1(ref(strVal), valid(strVal, 2), strRet1); //strRet1 : "test" // 为get_valid_string绑定参数。三个参数分别为:占位符、函数指针、占位符,且第一个与第三个参数绑定位置调换。 wstring strRet2; auto get_valid2 = bind(get_valid_string, _3, valid, _1); get_valid2(strRet2, valid(strVal, 2), ref(strVal)); //strRet2: "test"

    注意ref 、&及占位符的使用 标准库中旧版本的 bind1st ,bind2nd 分别绑定函数的第一个参数、第二个参数,无法绑定更多的参数

    补充: std:function和std::bind https://www.jianshu.com/p/f191e88dcc80

    Processed: 0.020, SQL: 9