c++ - 依赖于其他模板参数的模板参数?

标签 c++ c++11 templates eigen eigen3

我发现了一些类似的问题(例如 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将取决于 rowscols .上面的代码导致编译器错误(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/

相关文章:

c++ - 为什么通过指针交换在 C++ 中的 vector 中不起作用?

c++ - 在模板元编程中使用 "struct xxx<>::val"导致错误

c++ - 在没有模板化类的情况下存储 lambda

c++ - 检查类型是否在可变参数模板参数包中传递

c# - C++ 客户端,C# 服务器

c++ - 如何以惯用的方式实现 C++ 序列化程序?

c++在类之间传递指针 - 访问其他类方法

c++ - 可以将 char* move 到 std::string 中吗?

c++ - 获取函数参数个数

c++ - 如何让本地匿名 C++ 函数对象使用包含方法的参数?