C++模板的用法<>

C++ usage of template<>

本文关键字:lt gt 用法 C++      更新时间:2023-10-16

可能重复:
模板<gt;在c++中

我在c++代码中看到了template<>

这是有效的语法吗?如果是,这意味着什么?

只要显式专门化模板(类或函数模板(或类模板的成员,就会使用它。第一组示例使用这个类模板和成员:

template<typename T>
struct A {
  void f();
  template<typename U>
  void g();
  struct B {
    void h();
  };
  template<typename U>
  struct C {
    void h();
  };
};

专门化和定义成员

// define A<T>::f() */
template<typename T>
void A<T>::f() { 
}
// specialize member A<T>::f() for T = int */
template<>
void A<int>::f() {
}
// specialize member A<T>::g() for T = float
template<>
template<typename T>
void A<float>::g() { 
}
// specialize member A<T>::g for T = float and
// U = int
template<>
template<>
void A<float>::g<int>() {
}

// specialize A<T>::B for T = int
template<>
struct A<int>::B {
  /* different members may appear here! */
  void i();
};
/* defining A<int>::B::i. This is not a specialization, 
 * hence no template<>! */
void A<int>::B::i() {
}
/* specialize A<T>::C for T = int */
template<>
template<typename U>
struct A<int>::C {
  /* different members may appear here! */
  void i();
};
/* defining A<int>::C<U>::i. This is not a specialization, 
 * BUT WE STILL NEED template<>.
 * That's because some of the nested templates are still unspecialized.
 */
template<>
template<typename U>
void A<int>::C<U>::i() {
}

专门化非成员类模板的示例

template<typename T>
struct C {
  void h();
};
/* explicitly specialize 'C' */
template<>
struct C<int> {
  /* different members may appear here */ 
  void h(int);
};
/* define void C<int>::h(int). Not a specialization, hence no template<>! */
void C<int>::h(int) { 
}
/* define void C<T>::h(). */
template<typename T>
void C<T>::h() {
}

是的,这是有效的-它用于类模板专门化。。。看见http://www.cplusplus.com/doc/tutorial/templates/