c++的模板具备非常的超能力,能将通用的东西模板化,而由模板技术衍生出来的三大库又是那么的神奇(BOOST LOKI STL),而模板所能做的工作远远不止于这些,如果大家熟悉BOOST的元编程,就可以看出为了能降低程序的计算时间,将其转移至编译器,由编译器来进行计算。模板编程的课伸缩性非常好,给我们的编程带来了很大的帮助,更主要的是在编译器对我们的帮助。这里我给大家简单介绍一下模板一个很重要的入门技术,模板的偏特化。所谓模板的偏特化,其实是两个部分,一个是部分特化,一个是全部特化。部分偏化表示模板参数中有一部分被现有的类型所实现,而全部特化则是将所有的类型由现有的类型实现。
如下例子
#include <iostream> #include <cassert> using namespace std; template<class T, class U> class GenericBase { public: static enum {value = 0,}; }; //部分特化 template<class U> class GenericBase<int, U> { public: static enum {value = 1,}; }; //部分特化 template<class T> class GenericBase<T, char> { public: static enum {value = 2,}; }; //全部特化 template<> class GenericBase<int, char> { public: static enum {value = 3,}; }; template<class T = void> class NullType {}; int _tmain(int argc, _TCHAR* argv[]) { //In MSVC NullType need to be NullType<> int value0 = GenericBase<NullType<>, NullType<>>::value; int value1 = GenericBase<int, NullType<>>::value; int value2 = GenericBase<NullType<>, char>::value; int value3 = GenericBase<int, char>::value; assert(value0 == 0); assert(value1 == 1); assert(value2 == 2); assert(value3 == 3); std::cout<<"test has passed!"<<std::endl; char c = getchar(); return 0; }
#include <iostream> #include <cassert> using namespace std; //第一种实现方法 template<class T, class U> struct is_same_type { static const bool value = false; }; template<class T> struct is_same_type<T, T> { static const bool value = true; }; //第二中实现方法 template<class T, class U> struct is_same2 { template<class T> struct InStruct { static const bool value = false; }; template<> struct InStruct<T> { static const bool value = true; }; static const bool value = InStruct<U>::value; }; //------------------------------------------------------------ template<class T> struct is_int { static const bool value = false; }; template<> struct is_int<int> { static const bool value = true; }; //--------------------------------------------------------------- template<class T> struct is_double { static const bool value = false; }; template<> struct is_double<double> { static const bool value = true; }; //------------------------------------------------------- template<class T = void> struct NullType { typedef T param_type; }; int _tmain(int argc, _TCHAR* argv[]) { //In MSVC NullType need write to be NullType<> to use default type assert((!is_same_type<double, int>::value)); assert((is_same_type<double, double>::value)); assert((!is_same2<double,int>::value)); assert((is_same2<int, int>::value)); assert((is_int<int>::value)); assert((!is_int<double>::value)); assert((!is_int<NullType<>>::value)); assert((!is_double<int>::value)); assert((is_double<double>::value)); assert((!is_double<NullType<>>::value)); std::cout<<"test passed!"; char c = getchar(); return 0; }
原文:http://blog.csdn.net/davidsu33/article/details/22643781