c++函数指针模板又一次说明(225)

函数指针又一次说明

今天看rapidjson的源码,看到一句默认操作符转换函数指针的代码懵逼了居然。。
好歹也是读了十来本c++的书了,还这么2。
顺便做笔记。

  • 按照effictive说法,结构体比函数指针快。所以用operator()代替函数指针
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
//我按照它代码的写法,尝试了下。感觉默认指针函数只能用在if语句上来走个默认转换
struct Prs {
typedef bool (Prs::*Boolt)() const;
public:
bool m_bR;
operator Boolt() const {
return !IsEr() ? &Prs::IsEr : NULL;
};
bool IsEr() const
{
return m_bR == 0;
}
};
int ah(int a, int b, Prs &f, Prs::Boolt df)
{
if ((f.*df)())
{
return a+b;
}
return a-b;
}
Prs d;
d.m_bR = 1;
if (d)
{
int f = ah(1, 2, d, d);
}
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
//调用函数指针这个看上去没有创建对象,其实是初始化了一个临时对象再来调用它的operator()函数
//感觉用这个方法方便点
template<typename TR, typename TP>
struct PrsT {
public:
TR operator() (TP a, TP b){
return a+b;
}
};
template<typename TR, typename TP, typename Fun>
TR aht(TR a, TP b, Fun f)
{
return f(a, b);
}
struct Prs {
typedef bool (Prs::*Boolt)() const;
public:
bool m_bR;
operator Boolt() const {
return !IsEr() ? &Prs::IsEr : NULL;
};
bool IsEr() const
{
return m_bR == 0;
}
};
int ff = aht(1, 2, PrsT<int, int>());
// //