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

Vij*_*jay 39 c++ templates

template<>
class A{
//some class data
};
Run Code Online (Sandbox Code Playgroud)

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

Xeo*_*Xeo 62

template<>告诉编译器遵循模板特化,特别是完全特化.通常,class A必须看起来像这样:

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

template<>
class A<int>{
  // special implementation for ints
};
Run Code Online (Sandbox Code Playgroud)

现在,无论何时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
}
Run Code Online (Sandbox Code Playgroud)

通常,您不应该专门化函数,因为简单的重载通常被认为是优越的:

void foo(int i){
  // better
}
Run Code Online (Sandbox Code Playgroud)

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

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

template<class T1>
class B<T1, int>{
};
Run Code Online (Sandbox Code Playgroud)

工作方式作为一个完整的专业化相同,只是专业版何时使用,第二个模板参数是一个int(如B<bool,int>,B<YourType,int>等).

  • +1很好的答案!也许您应该补充一点,这是一个完整的模板专业化.即使..使用一个模板参数,也无法进行部分专业化. (2认同)

Joh*_*eek 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
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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


Rob*_*obH 7

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

template<>
class A<foo> {
// some stuff
};
Run Code Online (Sandbox Code Playgroud)

...这将是foo类型的模板特化.