Tho*_*ger 6 c++ class-template eigen template-argument-deduction c++17
我正在编写一个利用Eigen数据类型的通用类。我已经遇到了将构造函数参数分配给类成员变量的问题。我的代码的简化版本是:
template <typename Derived>
class A
{
public:
Eigen::Matrix<Derived> M; // error C2976: too few template parameters
A(const Eigen::DenseBase<Derived> & V)
{
M = V.eval(); // I would want to snapshot the value of V.
}
};
Run Code Online (Sandbox Code Playgroud)
我的问题是,现在M应该是哪种数据类型?我尝试了多种选择,例如:
Eigen::internal::plain_matrix_type_column_major<Derived> M;
Eigen::DenseBase<Derived> M;
Run Code Online (Sandbox Code Playgroud)
但是它们只会产生不同的错误。请注意,我使用C ++ 17并期望从构造函数中推断类模板参数。
Eigen::Matrix变量的声明M应该是这样的:
Eigen::Matrix<typename Derived::Scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> M;
Run Code Online (Sandbox Code Playgroud)
然后你的代码将被编译。见演示。
可以在此链接中找到每个模板参数的详细说明。
您的容器需要实际的“普通类型”作为模板参数:
template <typename PlainType>
class A
{
PlainType M;
public:
template<class Derived>
A(const Eigen::MatrixBase<Derived> & V) : M(V) {}
};
Run Code Online (Sandbox Code Playgroud)
并且还需要一个额外的模板推导规则:
template<class Derived>
A(const Eigen::MatrixBase<Derived> & V) -> A<typename Derived::PlainObject>;
Run Code Online (Sandbox Code Playgroud)
使用示例(在 godbolt 上):
template<class X>
void bar(X&); // just to read full type of A
void foo(Eigen::Matrix2d const& M)
{
A a = M*M;
bar(a); // calls bar<A<Matrix2d>>();
}
Run Code Online (Sandbox Code Playgroud)