现在的位置: 首页 > 综合 > 正文

模板的偏特化

2018年03月30日 ⁄ 综合 ⁄ 共 782字 ⁄ 字号 评论关闭
template <class Window, class Controller>
class Widget
{
     ....
};

// 特化
// 其中 ModalDialog 和 MyController 是另外定义的 class
template<>
class Widget<ModalDialog, MyController> // 编译器只看这里是否符合指定的类型
{
     ....
};

// 偏特化
// 其中 Window 是泛化类型参数,MyController 是具体类型
tempalte <class Window>
class Widget<Window, MyController> // 同理,
编译器只看这里是否符合指定的类型
{
    ....
};
// 还可以这样
template <class ButtonArg>
class Widget<Button<ButtonArg>, MyController>
{
   ...
};


1 class 和 struct 可以实现偏特化,编译器会把目前存在的偏特化和全特化作比较,并找出其中最合适者.
2 偏特化机制不能用在函数身上(不论成员函数或非成员函数)
  *虽然你可以全特化 class template 中的成员函数,但你不能偏特化它们。
  *不能偏特化 namespace-level (non-member) 函数。最接近 "namespace-level template functions" 偏特化机制是函数重载。意味着你对“函数参数”(而非返回值型别或内部所用型别)有很精致的特化能力。
template <class T, class U> T Fun(U obj); // primary template
// template <class U> void Fun<void, U>(U obj); // illegal partial specialization
tempate <class T> T Fun(Window obj> // legal (overloading)

抱歉!评论已关闭.