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

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

2022-9-13 08:37
3616

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

Chapter 3 通用编程

类型推导和定义

C++11 定义类型

有两种定义类型的方式,一个是typedef,一个是using。

 

建议以后使用using,而不是typedef。

1
2
3
4
5
typedef double value_type;
using value_type = double;
 
typedef float (*float_fun1)(float,int);
using float_fun2 = float(*)(float,int);

模板特化

为类特化一种类型

1
2
3
4
5
template<>
class vector<bool>
{
    // ...
};

类的偏特化

解决如下繁琐工作

1
2
3
4
5
6
7
8
template<>
class vector<complex<float>>;
 
template<>
class vector<complex<double>>;
 
template<>
class vector<complex<long double>>;

方案

1
2
3
template<typename Real>
class vector<complex<Real>>
{ ... };

函数偏特化

函数模板实际上不能部分特化。但是我们通过函数重载提供了特化的实现。

1
2
3
4
5
6
7
8
9
10
template<typename T>
inline T abs(const T& x)
{
    return x<T(0)-x:x;
}
template <typename T>
inline T abs(const std::complex<T>& x)
{
    return sqrt(real(x)*real(x)+imag(x)*imag(x));
}

C++14 简化了返回值的书写

1
2
3
4
5
6
7
template <typename T> struct abs_functor;
 
template <typename T>
decltype(auto) abs(const T& x)
{
    return abs_functor<T>{}(x);
}

C++11 的书写格式

1
2
3
4
5
template <typename T>
auto abs(const T& x) -> decltype(abs_functor<T>{}(x))
{
return abs_functor<T>{}(x);
}

C++03 版本

1
2
3
4
5
6
template <typename T>
typename abs_functor<T>::result_type
abs(const T& x)
{
    return abs_functor<T>{}(x);
}

C++17 结构化绑定用户类型


[培训]《安卓高级研修班(网课)》月薪三万计划

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