官术网_书友最值得收藏!

  • Mastering C++ Programming
  • Jeganathan Swaminathan
  • 156字
  • 2021-07-02 18:28:46

The std::invoke( ) method

The std::invoke() method can be used to call functions, function pointers, and member pointers with the same syntax:

#include <iostream>
#include <functional>
using namespace std;

void globalFunction( ) {
cout << "globalFunction ..." << endl;
}

class MyClass {
public:
void memberFunction ( int data ) {
std::cout << "\nMyClass memberFunction ..." << std::endl;
}

static void staticFunction ( int data ) {
std::cout << "MyClass staticFunction ..." << std::endl;
}
};

int main ( ) {

MyClass obj;

std::invoke ( &MyClass::memberFunction, obj, 100 );
std::invoke ( &MyClass::staticFunction, 200 );
std::invoke ( globalFunction );

return 0;
}

The preceding code can be compiled and the output can be viewed with the following commands:

g++-7 main.cpp -std=c++17
./a.out

The output of the preceding program is as follows:

MyClass memberFunction ...
MyClass staticFunction ...
globalFunction ...

The std::invoke( ) method is a template function that helps you seamlessly invoke callable objects, both built-in and user-defined.

主站蜘蛛池模板: 门头沟区| 大兴区| 孟津县| 黑龙江省| 太白县| 河池市| 灌阳县| 修水县| 乌兰浩特市| 衡东县| 青州市| 沅江市| 庐江县| 综艺| 吴忠市| 黄冈市| 二连浩特市| 汤原县| 伊通| 宜州市| 清流县| 紫云| 蓬莱市| 岑巩县| 文安县| 凤阳县| 五华县| 兴隆县| 泗洪县| 安顺市| 库伦旗| 霍邱县| 泰安市| 郓城县| 中牟县| 犍为县| 县级市| 台中市| 沙雅县| 乐至县| 黄冈市|