参考:C++模板的偏特化与全特化
#includetemplate void fun(T1 t1, T2 t2) { std::cout << t1 << " " << t2 << std::endl; } template<> void fun (int t1, int t2) { std::cout << t1 << "+" << t2 << std::endl; } template class A { public: static void print() { T1 t1; T2 t2; std::cout << "原版模板类,类型为:" << typeid(t1).name() << " " << typeid(t2).name() << std::endl; } }; template class A { public: static void print() { int t1; T2 t2; std::cout << "偏特化模板类,类型为:" << typeid(t1).name() << " " << typeid(t2).name() << std::endl; } }; template <> class A { public: static void print() { int t1; float t2; std::cout << "全特化模板类,类型为:" << typeid(t1).name() << " " << typeid(t2).name() << std::endl; } }; int main() { fun(static_cast (1), static_cast (2)); // 调用原始模板函数 fun(static_cast (3), static_cast (4)); // 调用最匹配的全特化版本函数 A ::print(); A ::print(); A ::print(); system("pause"); }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)