【发布时间】:2016-04-08 15:23:07
【问题描述】:
我正在设置一个 c++(11) 程序,其中我使用了一个依赖于 2 个参数的模板类。大部分类都可以根据模板参数进行通用编写。只有少数功能需要专门的版本。这是一个重现我的问题的示例模式:
template<class T, int N>
class foo
{
// typedefs and members that depend on T and N
// but that can be written generically e.g. :
typedef std::array<T,N> myarray;
void myfunc(myarray tab);
};
// ...
template<class T, int N>
foo<T,N>::myfunc(myarray tab)
{
// generic version
}
// need specialization only of myfunc:
template<class T>
foo<T,1>::myfunc(myarray tab)
{
// specialized version for N=1
}
然后编译器抱怨:error: invalid use of incomplete type ‘class foo<T, 1>’ 关于然后行 template<class T> foo<T,1>::myfunc(myarray tab)
我发现唯一可行的解决方法是插入该类的完整副本及其专用版本:
template<class T>
class foo<T,1>
{
// recopy all the lines of class foo<T,N>, replacing N by 1
};
// duplicate as well all generic function definition with
// specialized versions <T,1> even when not needed
有什么很不满意的……
经过一些实验,我发现当模板仅使用1个参数时(例如template <int N> class foo{...};)似乎不会出现此问题,而是至少涉及2个参数时才会出现此问题。
这在 C++ 编程中是众所周知的吗?有没有更聪明的方法来解决我的问题? (我想创建一个没有专门功能的母类,然后让类 foo 从它继承,只保留专门的成员,以尽量减少“重复解决方法”)
感谢您的建议!
【问题讨论】:
标签: c++ templates template-specialization