c++ std::invoke
测试代码如下:
#include <iostream>
#include <functional>pair<int, int> getMinAndMax(int a, int b) {int min = a < b ? a : b;int max = a > b ? a : b;return make_pair(min, max);
}// 测试invoke函数的用法
void testInvoke() {// 调用普通函数pair<int, int> res = invoke(getMinAndMax, 9527, 1);cout << "min: " << res.first << ", max: " << res.second << endl;// 调用成员函数struct MyStru {string info;void test(int x) { std::cout << "x = " << x << std::endl; }static void staticFunc(string str) {std::cout << str << std::endl;}};MyStru myStruct;myStruct.info = "小甜甜";invoke(&MyStru::test, myStruct, 10);invoke(&MyStru::staticFunc, "牛夫人");// 调用lambda表达式invoke([](string str) { std::cout << str << std::endl; }, "我对你的敬仰如滔滔江水连绵不绝。");// 通过智能指针调用auto ptr = std::make_unique<MyStru>();invoke(&MyStru::test, myStruct, 9527);// 修改成员变量cout << "修改前info: " << myStruct.info << endl;invoke(&MyStru::info, myStruct) = "一个月几百块你玩什么命啊";cout << "修改后info: " << myStruct.info << endl;// 调用仿函数:struct Functor {void operator()(const string& str) const {std::cout << str << std::endl;}};Functor f;std::invoke(f, "段王爷");
}
打印:
ok.