依赖于其他模板参数的模板参数?

Ash*_*Ash 4 c++ templates eigen c++11 eigen3

我发现了一些类似的问题(例如 这个),但没有一个真正回答我的问题.请考虑以下代码段:

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

正如您在专业化中所看到的,类型arrtype将取决于rowscols.上面的代码导致编译器错误(g ++ 5.4.0):

invalid use of incomplete type ‘class Variance<rows, cols, Eigen::Matrix<double, rows, cols> >
Run Code Online (Sandbox Code Playgroud)

我已经尝试typename arrtype<rows, cols>过模板声明,但后来抱怨这arrtype 不是一种类型,这是有道理的.

使用依赖于其他模板类型的模板化类型的正确方法是什么?

for*_*818 5

这是您的代码的简化版本:

template<size_t rows, size_t cols> struct Foo {   double foo(); };

template<size_t rows> double Foo<rows,3>::f() { return 3;}
Run Code Online (Sandbox Code Playgroud)

你得到的错误:

error: invalid use of incomplete type ‘struct Foo<rows, 3ul>’
double Foo<rows,3>::f() { return 3;}
Run Code Online (Sandbox Code Playgroud)

问题实际上是你的模板参数之一取决于其他模板参数,但问题是你不能部分专门化一个成员而不部分专门化这个类.

这有效:

template<size_t rows, size_t cols> struct Foo {   double foo(); };

template<size_t rows> struct Foo<rows,3> { double f() { return 3;}  };
Run Code Online (Sandbox Code Playgroud)

  • 要完成,根据上下文,将`f`设为自由函数以启用部分特化可能是个好主意. (2认同)