我发现了一些类似的问题(例如 this ),但没有一个能真正回答我的问题。考虑这个代码片段:
template<unsigned int rows, unsigned int cols,typename arrtype>
class Variance
{
double f(const arrtype &);
};
template<unsigned int rows, unsigned int cols>
double Variance<rows,cols,Eigen::Matrix<double,rows,cols>>
::f(const Eigen::Array<double,rows,cols> & M)
{
//do stuff
}
正如您在特化中看到的,类型 arrtype
将取决于 rows
和 cols
.上面的代码导致编译器错误(g++ 5.4.0):
invalid use of incomplete type ‘class Variance<rows, cols, Eigen::Matrix<double, rows, cols> >
我试过了typename arrtype<rows, cols>
在模板声明中,但随后它提示 arrtype
不是类型,这是有道理的。
使用依赖于其他模板类型的模板类型的正确方法是什么?
最佳答案
这是您的代码的简化版本:
template<size_t rows, size_t cols> struct Foo { double foo(); };
template<size_t rows> double Foo<rows,3>::f() { return 3;}
你得到的错误:
error: invalid use of incomplete type ‘struct Foo<rows, 3ul>’
double Foo<rows,3>::f() { return 3;}
问题不在于您的模板参数之一依赖于其他模板参数,而在于您不能在不部分特化类的情况下部分特化成员。
这个有效:
template<size_t rows, size_t cols> struct Foo { double foo(); };
template<size_t rows> struct Foo<rows,3> { double f() { return 3;} };
关于c++ - 依赖于其他模板参数的模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904772/