Function-Template

This is for the readers who have basic c++ background. If you want to get the rough sketch of funtion template of c++, then there it is.

I suggest an online c++ compiler : http://coliru.stacked-crooked.com/ (You can test your simple programs on it.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <functional>
#include <array>
using namespace std;

std::function<int(int)> Functional;

int TestFunc(int a){ return a;}

auto lambdaFn = [](float a)->float{ return a; };

class Functor{
public:
int operator()(int a){return a;}
};

class TestClass{
public:
int ClassMember(int a) { return a; }
static int StaticMember(int a) { return a; }
};

int main()
{

Functional = TestFunc;
int result = Functional(10); //10
cout << "TestFunc:"<< result << endl;


Functional = lambdaFn;
result = Functional(22.00); //22
cout << "Lambda:"<< result << endl;


Functor testFunctor;
Functional = testFunctor;
result = Functional(30); //30
cout << "Functor:"<< result << endl;


TestClass testObj;
Functional = std::bind(&TestClass::ClassMember, testObj, std::placeholders::_1);
result = Functional(40); //40
cout << "TestClass:"<< result << endl;


Functional = TestClass::StaticMember;
result = Functional(50); //50
cout << "TestClass(static):"<< result << endl;
return 0;
}

function is a kind of wrapper,which provides a way to handle several funtion-like forms uniformly. If you know polymorphism, then this is easy to understand.

Let’s see another code segment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <functional>
#include <map>
using namespace std;

int add(int x,int y){return x+y;}

struct divide
{
int operator()(int denominator,int divisor)
{
return denominator/divisor;
}
};

int main()
{

map<char,function<int(int,int)>> op =
{
{'+',add},
{'/',divide()},
{'-',[](int i,int j){return i-j;}}
};
cout << op['+'](1, 2) << endl; //3
cout << op['-'](1, 2) << endl; //-1
cout << op['/'](1, 2) << endl; //0
}

Reference: https://www.cnblogs.com/reboost/p/11076511.html


Your Majesty, coding and blogging is hard, but a cup of tea/coffee would be the best reward. Scan the QRcode below, I’ll swear my allegiance to you. :) memeda

Author

Keneyr

Posted on

2020-03-12

Updated on

2020-03-12

Licensed under

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×