部分模板特化的"无效使用不完整类型"错误

Jes*_*der 31 c++ gcc templates partial-specialization

以下代码:

template <typename S, typename T>
struct foo {
   void bar();
};

template <typename T>
void foo <int, T>::bar() {
}
Run Code Online (Sandbox Code Playgroud)

给了我错误

invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'
Run Code Online (Sandbox Code Playgroud)

(我正在使用gcc.)我的部分特化的语法错了吗?请注意,如果我删除第二个参数:

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

template <>
void foo <int>::bar() {
}
Run Code Online (Sandbox Code Playgroud)

然后它正确编译.

cop*_*pro 38

你不能部分专门化一个功能.如果您希望在成员函数上执行此操作,则必须部分专门化整个模板(是的,这很烦人).在一个大的模板类上,要部分专门化一个函数,你需要一个解决方法.也许模板化的成员结构(例如template <typename U = T> struct Nested)可以工作.否则,您可以尝试从另一个部分特化的模板派生(如果您使用this->member表示法,则工作,否则您将遇到编译器错误).


Ech*_*tor 7

虽然coppro已经提到了两个解决方案,而Anonymous解释了第二个解决方案,但我花了很长时间来理解第一个解决方案.也许以下代码对于在这个网站上磕磕绊绊的人有帮助,这个网站在谷歌中仍然排名很高,就像我一样.示例(将numericT的vector/array/single元素作为dataT传递,然后通过[]或直接访问它)当然有点人为,但应该说明你如何通过包装它实际上非常接近部分特化成员函数在一个部分专业的课堂上.

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


小智 5

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

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.
    }
};
Run Code Online (Sandbox Code Playgroud)

注意:这是从我正在处理的事情中匿名的。当您有一个包含大量成员的模板类并且您只想添加一个函数时,您也可以使用它。