#include <iostream> #include <string> #include <vector> #include <array> // 变量模板,这种定义最好不要出现在函数内部或块作用域内部 template<typename T> T var{}; // 可以进行初始化,也可以不初始化 template<typename U> // constexpr修饰的需要进行初始化,3.24对应类型只能是float、double等数字类型 // std::string等其他类型,不能转换,会编译错误 constexpr U cvar{3.24}; // 函数模板、类模板有默认模板参数,变量模板当然也有默认模板参数 template<typename T=int> T defaultVar{}; void Test(){ var<int> = 10; std::cout<<var<int><<std::endl; var<std::string> = "hello"; std::cout<<var<std::string><<std::endl; std::cout<<cvar<float><<std::endl; std::cout<<cvar<double><<std::endl; // std::cout<<cvar<std::string><<std::endl; // error,not convertiable std::cout<<defaultVar<><<std::endl;// use default template para type defaultVar<std::string> = "world"; defaultVar<std::vector<int>> = {1,2,3,4}; std::cout<<defaultVar<std::string><<std::endl; for (auto it: defaultVar<std::vector<int>>) { std::cout<<it<<std::endl; } } // 同样可以使用非类型模板参数对变量模板进行参数化 template<size_t N> std::array<int, N> arr{}; template<auto N> decltype(N) dval = N; void Test1(){ arr<3> = {1,2,3}; for (auto it: arr<3>) { std::cout<<it<<std::endl; } std::cout<<dval<10><<std::endl; std::cout<<dval<'a'><<std::endl; } // 成员变量模板化 template<typename T> struct Member{ static const int max{10}; std::string name{"ts"}; }; // 定义变量模板替换类成员变量 template<typename T> int maxType = Member<T>::max; void Test2(){ auto intTypeVar = Member<int>::max; auto strTypeVar = Member<std::string>::max; std::cout<<intTypeVar<<std::endl; std::cout<<strTypeVar<<std::endl; std::cout<<maxType<int><<std::endl; std::cout<<maxType<std::string><<std::endl; } int main() { Test(); Test2(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter