我有一个问题,我想在下面的代码中专门化模板类的模板成员函数。这个问题的答案explicit specialization of template class member function似乎表明它无法完成。这是正确的,如果是这样,我可以使用任何解决方法,以便通过内联 inc 函数在编译时扩展?
非常感谢!
#include <iostream>
#include <cstdio>
template <class IT, unsigned int N>
struct IdxIterator {
private:
int startIdx[N], endIdx[N];
int curIdx[N];
IT iter;
public:
IdxIterator(IT it, int cur[], int start[], int end[]): iter(it) {
for (int i = 0; i < N; i++) {
curIdx[i] = cur[i];
startIdx[i] = start[i];
endIdx[i] = end[i];
}
}
template <int dim>
inline void inc() {
curIdx[dim]++;
if (curIdx[dim] > endIdx[dim]) {
if (dim > 0) {
curIdx[dim] = startIdx[dim];
inc<dim-1>();
}
}
}
// how to declare this specialization?
template <> template <>
inline void inc<-1>() {
std::cerr << "IdxIterator::inc(" << -1 << ") dim out of bounds!\n";
throw 1;
}
inline IdxIterator<IT, N> operator++() {
iter++;
inc<N-1>();
return *this;
}
};
int main(int argc, char** argv) {
int *buf = new int[100];
int start[1], end[1];
start[0] = 0; end[0] = 99;
IdxIterator<int*, 1> it(buf, start, start, end);
++it;
return 0;
}
G++ 吐出:
test2.cpp:32:13:错误:非命名空间范围“struct IdxIterator”中的显式特化 test2.cpp:32:25:错误:非命名空间范围“struct IdxIterator”中的显式特化 test2.cpp:33:23:错误:主模板 test2.cpp 声明中的模板 ID 'inc<-0x00000000000000001>':在成员函数 'void IdxIterator::inc() [with int dim = -0x000000000000003fe, IT = int*, unsigned int N = 1u ]':test2.cpp:27:9:错误:模板实例化深度超过最大值 1024(使用 -ftemplate-depth= 增加最大值)实例化 'void IdxIterator::inc() [with int dim = -0x000000000000003ff,IT = int*, unsigned int N = 1u]' test2.cpp:27:9: 从'void IdxIterator::inc() [with int dim = -0x00000000000000001, IT = int*, unsigned int N = 1u]'递归实例化test2.cpp:27:9:从 'void IdxIterator::inc() [with int dim = 0, IT = int*, unsigned int N = 1u]' test2.cpp:41:5: 从 'IdxIterator IdxIterator::operator++() [with IT = int*, unsigned int N = 1u]' test2.cpp:53:5: 从这里实例化
test2.cpp:在全局范围内:test2.cpp:22:15:警告:内联函数 'void IdxIterator::inc() [with int dim = -0x000000000000003ff, IT = int*, unsigned int N = 1u]' 使用但从未定义[默认启用]