问题描述
以下代码:
template <typename S, typename T>
struct foo {
void bar();
};
template <typename T>
void foo <int, T>::bar() {
}
给我错误
invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'
部分专业化错了?注意,如果我删除第二个参数:
(I'm using gcc.) Is my syntax for partial specialization wrong? Note that if I remove the second argument:
template <typename S>
struct foo {
void bar();
};
template <>
void foo <int>::bar() {
}
那么它会正确编译。
推荐答案
您不能部分专门化一个函数。如果你希望在成员函数上这样做,你必须部分专门化整个模板(是的,它是刺激)。在大型模板类上,要部分专门化一个函数,您需要一个解决方法。也许模板成员结构(例如 template< typename U = T> struct Nested
)将工作。或者你可以尝试从另一个部分专门化的模板派生(如果你使用 this->成员
符号,否则会遇到编译器错误)。
You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. template <typename U = T> struct Nested
) would work. Or else you can try deriving from another template that partially specializes (works if you use the this->member
notation, otherwise you will encounter compiler errors).
这篇关于“不完全类型的无效使用”错误与部分模板专门化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!