答案 0 :(得分:8)
只要您明确地专门化模板(类或函数模板)或类模板的成员,就会使用它。第一组示例使用此类模板和成员:
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() {
}
答案 1 :(得分:5)
是的,这是有效的 - 它用于课程模板专业化...请参阅http://www.cplusplus.com/doc/tutorial/templates/