template<>是什么意思用C ++中的空尖括号?

时间:2011-06-09 06:18:52

标签: c++ templates

template<>
class A{
//some class data
};

我多次见过这种代码。 在上面的代码中template<>有什么用? 我们需要强制使用它的情况是什么?

3 个答案:

答案 0 :(得分:60)

template<>告诉编译器接下来是模板专业化,特别是完全专业化。通常,class A必须看起来像这样:

template<class T>
class A{
  // general implementation
};

template<>
class A<int>{
  // special implementation for ints
};

现在,只要使用A<int>,就会使用专用版本。您还可以使用它来专门化函数:

template<class T>
void foo(T t){
  // general
}

template<>
void foo<int>(int i){
  // for ints
}

// doesn't actually need the <int>
// as the specialization can be deduced from the parameter type
template<>
void foo(int i){
  // also valid
}

通常情况下,您不应该将功能专门化为simple overloads are generally considered superior

void foo(int i){
  // better
}

现在,为了使其成功,以下是部分专业化

template<class T1, class T2>
class B{
};

template<class T1>
class B<T1, int>{
};

与完全专业化的工作方式相同,只要在第二个模板参数为int时使用专用版本(例如B<bool,int>B<YourType,int>等)。< / p>

答案 1 :(得分:8)

template<>引入了模板的完全特化。你的例子本身并不实际有效;在它变得有用之前你需要一个更详细的场景:

template <typename T>
class A
{
    // body for the general case
};

template <>
class A<bool>
{
    // body that only applies for T = bool
};

int main()
{
    // ...
    A<int>  ai; // uses the first class definition
    A<bool> ab; // uses the second class definition
    // ...
}

它看起来很奇怪,因为它是一个更强大功能的特殊情况,称为“部分特化”。

答案 2 :(得分:7)

看起来不对。现在,您可能已经写了:

template<>
class A<foo> {
// some stuff
};

...对于foo类型,它将是模板特化