0%

C++11 中的模板改进

C++11 中该进了模板,看看还是比较有用的, 终于理解上古代码里为什么模板尖括号里总是多留一个空格了

原文地址 mp.weixin.qq.com

C++11 关于模板有一些细节的改进:

  • 模板的右尖括号
  • 模板的别名
  • 函数模板的默认模板参数

模板的右尖括号

C++11 之前是不允许两个右尖括号出现的,会被认为是右移操作符, 所以需要中间加个空格进行分割,避免发生编译错误.

1
2
3
4
5
int main() {
std::vector<std::vector<int>> a; // error
std::vector<std::vector<int> > b; // ok
}

这个我之前都不知道,我开始学编程的时候就已经是 C++11 的时代啦.

模板的别名

C++11 引入了 using, 可以轻松的定义别名,而不是使用繁琐的 typedef.

1
2
typedef std::vector<std::vector<int>> vvi; // before c++11
using vvi = std::vector<std::vector<int>>; // c++11

使用 using 明显简洁并且易读,大家可能之前也见过使用 typedef 定义函数指针之类的操作,那烂代码我就不列出来了, 反正我是看不懂也不想看... 以后都可以使用 using, 额还是列出来吧.

1
2
typedef void (*func)(int, int); // 啥玩意, 看不懂
using func = void (*)(int, int); // 起码比typedef容易看的懂吧

上面的代码使用 using 起码比 typedef 容易看的懂一些吧, 但是我还是看不懂,因为我从来不用这种来表示函数指针,用 std::function()std::bind()std::placeholder()lambda 表达式它不香吗.

函数模板的默认模板参数

C++11 之前只有类模板支持默认模板参数,函数模板是不支持默认模板参数的, C++11 后都支持.

1
2
3
4
5
6
7
8
9
template <typename T, typename U=int>
class A {
T value;
};
template <typename T=int, typename U> // error
class A {
T value;
};

类模板的默认模板参数必须从右往左定义,而函数模板则没有这个限制.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template <typename R, typename U=int>
R func1(U val) {
return val;
}
template <typename R=int, typename U>
R func2(U val) {
return val;
}
int main() {
cout << func1<int, double>(99.9) << endl; // 99
cout << func1<double, double>(99.9) << endl; // 99.9
cout << func1<double>(99.9) << endl; // 99.9
cout << func1<int>(99.9) << endl; // 99
cout << func2<int, double>(99.9) << endl; // 99
cout << func1<double, double>(99.9) << endl; // 99.9
cout << func2<double>(99.9) << endl; // 99.9
cout << func2<int>(99.9) << endl; // 99
return 0;
}

对于函数模板,参数的填充顺序是从左到右的.

参考资料

《深入应用 C++11:代码优化与工程级应用》

https://blog.csdn.net/tennysonsky/article/details/77817027

https://blog.csdn.net/wf19930209/article/details/79309881?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1

关于 C++11 对于模板的改进就讲到这里,请继续关注~

一文让你搞懂设计模式

RAII 妙用之 ScopeExit

RAII 妙用之计算函数耗时

一文吃透 C++11 中 auto 和 decltype 知识点

左值引用、右值引用、移动语义、完美转发, 你知道的不知道的都在这里

如果有任何问题或想法,可以 点此留言, 我会尽快回复哒!欢迎小伙伴们踊跃留言,希望这里是大家交流互通的平台~