(自用)template泛型编程,传function,lambda,仿函数,函数指针-例子

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
#include<bits/stdc++.h>

template<class S,class OP=S(*)(S,S)>
class SegmentTree
{
private:
OP op;
public:
SegmentTree(OP _op=OP()) : op(_op) {}
S f(S a,S b)
{
return op(a,b);
}
};

int mul(int a,int b)
{
return a*b;
}
struct Max
{
int operator()(int a, int b)
{
return std::max(a,b);
}
};

void mytest()
{
std::function<int(int,int)> add = [](int a,int b){return a+b;};
SegmentTree<int,decltype(add)>t1(add);
std::cout<<t1.f(3,5)<<"\n";//8

SegmentTree<int>t2(mul);
std::cout<<t2.f(3,5)<<"\n";//15

SegmentTree<int,Max>t3;
std::cout<<t3.f(3,5)<<"\n";//5
}
int main()
{
mytest();
return 0;
}