虽然 coppro 已经提到了两个解决方案,并且 Anonymous 解释了第二个,但我花了很长时间才理解第一个。也许下面的代码对偶然发现这个网站的人有帮助,这个网站在谷歌中仍然排名很高,比如我。该示例(将 numericT 的向量/数组/单个元素作为 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) ...
};