|
| 1 | +// |
| 2 | +// 2.6.cpp |
| 3 | +// c++1x tutorial |
| 4 | +// |
| 5 | +// created by changkun at shiyanlou.com |
| 6 | +// |
| 7 | +// 模板增强 |
| 8 | + |
| 9 | + |
| 10 | +#include <iostream> |
| 11 | +#include <vector> |
| 12 | +#include <string> |
| 13 | + |
| 14 | +template class std::vector<bool>; // 强行实例化 |
| 15 | +extern template class std::vector<double>; // 不在该编译文件中实例化模板 |
| 16 | + |
| 17 | + |
| 18 | +template< typename T, typename U, int value> |
| 19 | +class SuckType { |
| 20 | +public: |
| 21 | + T a; |
| 22 | + U b; |
| 23 | + SuckType():a(value),b(value){} |
| 24 | +}; |
| 25 | +// template< typename T> |
| 26 | +// typedef SuckType<std::vector<int>, T, 1> NewType; // 不合法 |
| 27 | + |
| 28 | +template <typename T> |
| 29 | +using NewType = SuckType<int, T, 1>; // 合法 |
| 30 | + |
| 31 | +// 默认模板类型 |
| 32 | +template<typename T = int, typename U = int> |
| 33 | +auto add(T x, U y) -> decltype(x+y) { |
| 34 | + return x+y; |
| 35 | +} |
| 36 | + |
| 37 | +// sizeof... |
| 38 | +template<typename... Args> |
| 39 | +void magic(Args... args) { |
| 40 | + std::cout << sizeof...(args) << std::endl; |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +// 1. 递归解参数包 |
| 45 | +template<typename T> |
| 46 | +void printf1(T value) { |
| 47 | + std::cout << value << std::endl; |
| 48 | +} |
| 49 | +template<typename T, typename... Args> |
| 50 | +void printf1(T value, Args... args) { |
| 51 | + std::cout << value << std::endl; |
| 52 | + printf1(args...); |
| 53 | +} |
| 54 | +// 2.初始化列表展开解参数包 |
| 55 | +template<typename T, typename... Args> |
| 56 | +auto printf2(T value, Args... args) { |
| 57 | + std::cout << value << std::endl; |
| 58 | + return std::initializer_list<T>{([&] { |
| 59 | + std::cout << args << std::endl; |
| 60 | + }(), value)...}; |
| 61 | +} |
| 62 | + |
| 63 | +int main() { |
| 64 | + |
| 65 | + std::vector<std::vector<int>> wow; // 注意尖括号 |
| 66 | + |
| 67 | + NewType<int> t; |
| 68 | + |
| 69 | + magic(); |
| 70 | + magic(1); |
| 71 | + magic(1,""); |
| 72 | + |
| 73 | + printf1(1, 2.3, "abc"); |
| 74 | + printf2(1, 2.3, "abc"); |
| 75 | + return 0; |
| 76 | +} |
0 commit comments