首页
社区
课程
招聘
[分享]《探索现代化C++》泛读笔记摘要8
2022-9-14 08:44 3852

[分享]《探索现代化C++》泛读笔记摘要8

2022-9-14 08:44
3852

《探索现代化C++》泛读笔记摘要8

Chapter 3 通用编程

非类型模板参数

1
2
3
4
5
6
7
template<typename T,int Size = 3>
{/*...*/};
 
fsize_vector<float> v,w,x,y;
 
fsize_vector<float,4> space_time;
fsize_vector<float,11> string;

C++17 推导非类型参数

1
2
3
4
5
6
template<auto Value>
struct integral_constant_c
    : std::integral_constant<decltype(Value),Value>
{};
 
using f_type = integral_constant_c<flase>;

仿函数

书上举例了写了一个求近似导数的算法代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
double fin_diff(double f(double), double x, double h)
{
    return (f(x+h)-f(x))/h;
}
 
double sin_plus_cos(double x)
{
    return sin(x)+cos(x);
}
 
int main() {
    cout<<fin_diff(sin_plus_cos,1.,0.001)<<'\n';
}

这里遇到一个问题,如果我们要求二阶近似导数的话,发现fin_diff无法调用自身了,因为他需要三个参数,于是作者推出使用C++仿函数作为解决方案。将sin_plus_cos实现为了仿函数。

 

对象可以像函数一样调用。

1
2
3
4
5
6
7
struct sc_f
{
    double operator() (double x) const
    {
        return sin(x)+cos(x);
    }
};

内部带状态的仿函数

1
2
3
4
5
6
7
8
9
10
11
12
13
class psc_f
{
public:
    psc_f(double alpha) :alpha(alpha){}
 
    double operator() (double x) const
    {
        return sin(alpha * x) +cos(x);
    }
private:
 
    double alpha;
};

类似函数的模板参数

有了仿函数,我们再借助模板,让其发挥更大的效益,不局限于一种调用方式。

1
2
3
4
5
6
7
8
9
10
11
12
template <typename F, typename T>
T inline fin_diff(F f, const T& x, const T& h)
{
return (f(x+h) - f(x)) / h;
}
int main()
{
    psc_f psc_o{1.0};
    cout ≪ fin_diff(psc_o, 1., 0.001) ≪ endl;
    cout ≪ fin_diff(psc_f{2.0}, 1., 0.001) ≪ endl;
    cout ≪ fin_diff(sin_plus_cos, 0., 0.001) ≪ endl;
}

[培训]二进制漏洞攻防(第3期);满10人开班;模糊测试与工具使用二次开发;网络协议漏洞挖掘;Linux内核漏洞挖掘与利用;AOSP漏洞挖掘与利用;代码审计。

收藏
点赞0
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回