阅读笔记
原文链接
控制流
constexpr 关键字的存在,可以将表达式或者函数在编译时,就转为为函数结果,我们可以利用这一点,将其在条件判断当中使用。
例如:

模板
模板的哲学在于将一切能够在编译期处理的问题丢到编译期进行处理,仅在运行时处理那些最核心的动态服务
- C++11 引入了外部模板,使我们能够显式的通知编译器何时进行模板的实例化,或者不进行实例化。
1 2
| template class std::vector<bool>; extern template class std::vector<double>;
|
using与模板
对比以下两中方法,来定义函数指针
1 2 3 4 5 6 7 8 9 10
|
typedef void (*handler)(int, const char*);
using handler = void(*)(int, const char*);
using TrueDarkMagic = MagicType<std::vector<T>, std::string>;
|
变长参数模板
写法:
1
| template<typename... Ts> class Magic;
|
Magic 的对象,能够接受不受限制个数的 typename 作为模板的形式参数,例如下面的定义:
1 2 3 4
| class Magic<int, std::vector<int>, std::map<std::string, std::vector<int>>> darkMagic;
|
解包参数
1.递归模板函数(比较冗余)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <iostream> template<typename T0> void printf1(T0 value) { std::cout << value << std::endl; }
template<typename T, typename... Ts> void printf1(T value, Ts... args) { std::cout << "我的大小:" << sizeof...(args) << std::endl; std::cout << value << std::endl; printf1(args...); }
int main() { printf1(1, 2, "123", 1.1); return 0; }
|
输出
1 2 3 4 5 6 7
| 我的大小:3 1 我的大小:2 2 我的大小:1 123 1.1
|
2.变参模板展开