只特化一个类模板的某一个成员函数
有类定义如下
template<class T, unsigned B>
class Base
{
//应被特化的函数
void Func(){}
};
template<class T, unsigned B>
class Base
{
public:
void Func()
{
if (B == 16)
{
cout << "helloworl";
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base<int,16> base;
base.Func();
}
#include <iostream>
namespace
{
template <bool,typename = void> struct enable_if { };
template <typename T> struct enable_if<true,T> { typedef T type; };
}
template<class T, unsigned B>
struct Base
{
template <unsigned N = B>
typename ::enable_if<16!=N>::type
Func () { std::cout << "primary" << std::endl; }
template <unsigned N = B>
typename ::enable_if<16==N>::type
Func () { std::cout << "specialization" << std::endl; }
};
int main ()
{
{
Base<int,0> b;
b.Func();
}
{
Base<int,16> b;
b.Func();
}
return 0;
}
template<class T, unsigned B>错误的话,那这个呢?
class SpecialValue
{
public:
void Func();
};
template<class T, unsigned B>
void SpecialValue<T,B>::Func()
{
printf("Template Specialization Normal\n");
}
template<class T>
void SpecialValue<T,16>::Func()
{
printf("Template Specialization Value:16\n");
}
template<class T>
class SpecialType
{
public:
void Func();
};
template<class T>
void SpecialType<T>::Func()
{
printf("Template Specialization Type::Normal\n");
}
template<>
void SpecialType<long>::Func()
{
printf("Template Specialization Type::long\n");
}
#include <iostream>
namespace
{
template <bool,typename T,typename> struct conditional { typedef T type; };
template <typename T,typename U> struct conditional<false,T,U> {typedef U type; };
}
template<class T, unsigned B>
struct Base
{
void Func ()
{
typedef typename ::conditional<B!=16,primary_t,spec_t>::type type;
Func_impl(type());
}
private:
struct primary_t { };
struct spec_t { };
void Func_impl (primary_t) { std::cout << "primary" << std::endl; }
void Func_impl (spec_t ) { std::cout << "specialization" << std::endl; }
};
int main ()
{
{
Base<int,0> b;
b.Func();
}
{
Base<int,16> b;
b.Func();
}
return 0;
}