部分模板专业化“错误地使用不完整types”错误

以下代码:

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>' 

(我正在使用gcc。)我的部分专业化的语法是错误的? 请注意,如果我删除第二个参数:

 template <typename S> struct foo { void bar(); }; template <> void foo <int>::bar() { } 

那么它编译正确。

你不能部分地专门化一个function。 如果您希望在成员函数中这样做,则必须部分地专门化整个模板(是的,这很刺激)。 在一个大的模板类上,为了部分专门化一个函数,你需要一个解决方法。 也许模板成员结构(例如template <typename U = T> struct Nested )将工作。 否则,您可以尝试从另一个部分专门化的模板派生(如果使用this->member注释工作,否则会遇到编译器错误)。

如果您需要部分专门化构造函数,则可以尝试如下所示:

 template <class T, int N> struct thingBase { //Data members and other stuff. }; template <class T, int N> struct thing : thingBase<T, N> {}; template <class T> struct thing<T, 42> : thingBase<T, 42> { thing(T * param1, wchar_t * param2) { //Special construction if N equals 42. } }; 

注意:这是从我正在进行的工作中匿名化的。 当你有一个拥有大量成员的模板类时,你也可以使用它,而你只是想添加一个函数。

虽然coppro已经提到了两个解决scheme,Anonymous解释了第二个解决scheme,但是我花了相当长的时间来理解第一个解决scheme。 也许下面的代码有助于有人在这个网站上磕磕绊绊,这个网站仍然像我一样排在谷歌之首。 这个例子(把数字T的vector / array / single元素作为dataT传递,然后直接通过[]或直接访问它)当然是有些人为的,但是应该说明你实际上可以非常接近于通过包装来部分专门化一个成员函数在部分专业class。

 /* The following circumvents the impossible partial specialization of a member function actualClass<dataT,numericalT,1>::access as well as the non-nonsensical full specialisation of the possibly very big actualClass. */ //helper: template <typename dataT, typename numericalT, unsigned int dataDim> class specialised{ public: numericalT& access(dataT& x, const unsigned int index){return x[index];} }; //partial specialisation: template <typename dataT, typename numericalT> class specialised<dataT,numericalT,1>{ public: numericalT& access(dataT& x, const unsigned int index){return x;} }; //your actual class: template <typename dataT, typename numericalT, unsigned int dataDim> class actualClass{ private: dataT x; specialised<dataT,numericalT,dataDim> accessor; public: //... for(int i=0;i<dataDim;++i) ...accessor.access(x,i) ... };