在C++中,模板在代码重构方面起着重要作用,由于之前对模板一直不熟悉,现在总结一下有关模板特化的使用。
1.通过template<>实现特化,可以重写方法的实现
class Sparrow;
class Swallow;
class Turtledove;
template<class T>
class Fly
{
public:
static void funFly()
{
cout << "fly" << endl;
}
};
template<>
class Fly<Sparrow>
{
public:
static void funFly()
{
cout << "Sparrow fly" << endl;
}
};
template<>
class Fly<Swallow>
{
public:
static void funFly()
{
cout << "Swallow fly" << endl;
}
};
int main()
{
Fly<Sparrow>::funFly();
Fly<Swallow>::funFly();
Fly<Turtledove>::funFly();
return 0;
}
2.template class
template class Fly<Turtledove>;
typedef Fly<Turtledove> Temp;
int main()
{
Temp::funFly();
return 0;
}
模板了解的比较少,后续有接触会继续更新。