【问题标题】:Inherit from Eigen Matrix and construct or map from memory从 Eigen Matrix 继承并从内存中构造或映射
【发布时间】:2019-04-18 06:59:30
【问题描述】:

我正在使用 eigen 进行一些测试(作为我当前使用的 boost 矩阵的替代品),并且我试图为 Eigen Matrix 顶部的一个类定义 CTOR 我遇到了一段代码的问题,该代码会产生大量嘈杂的警告。问题显然是由于标量类型和标量类型上的指针之间的模板类型混淆。

欢迎所有帮助或建议, 谢谢。

我定义了以下模板类

template<typename T>
 class CVector : public Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign>
 {
  public:
   typedef typename Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::StorageOptions::AutoAlign> Base_Vector;
   .....

我使用 Eigen 文档提供的一段代码从 Eigen 对象和 3 个构造函数下面的几行构造函数

CVector(size_t size1) : Base_Vector(size1)
{}
CVector(size_t size1, T val): Base_Vector(size1)
{
    this->setConstant(5);
}
CVector(T* val_array, size_t val_array_size): Base_Vector(val_array_size)
{
    std::copy(val_array, val_array+val_array_size, this->data());
}

但是,当我尝试通过编写类似以下内容来使用它时,最后一个 CTOR 会引起很多警告:

   int tab [] = { 1,2,3,4,5 };
   CVector<int> v3(tab, 5);

从 VS'2015 我得到:

warning C4267: 'argument': conversion from 'size_t' to 'const int', possible loss of data
note: see reference to class template instantiation 'Eigen::internal::is_convertible_impl<unsigned __int64,int>' being compiled
note: see reference to class template instantiation 'Eigen::internal::is_convertible<std::T,int>' being compiled
with
[
    T=std::size_t
]
note: see reference to function template instantiation 'Eigen::Matrix<int,-1,1,0,-1,1>::Matrix<std::size_t>(const T &)' being compiled
with
[
    T=std::size_t
]
note: see reference to function template instantiation 'Eigen::Matrix<int,-1,1,0,-1,1>::Matrix<std::size_t>(const T &)' being compiled
with
[
    T=std::size_t
]
note: while compiling class template member function 'CVector<int>::CVector(T *,std::size_t)'
with
[
    T=int
]
note: see reference to function template instantiation 'CVector<int>::CVector(T *,std::size_t)' being compiled
with
[
    T=int
]
note: see reference to class template instantiation 'CVector<int>' being compiled

但另一方面,我使用时根本没有警告

float tab [] = { 1,2,3,4,5 };
CVector<float> v3(tab, 5);

【问题讨论】:

  • Eigen::Matrix 构造函数是什么样子的?可能它的 argument 成员变量专用于 int 类型,但您将 size_t 传递给构造函数 - 这两者之间的转换会产生警告。

标签: c++ pointers templates eigen


【解决方案1】:

Eigen 使用有符号类型来存储大小和索引。此类型为Eigen::Index,默认情况下是std::ptr_diff 的typedef。只需将 size_t 替换为 Eigen::Index 即可,在您这样做的同时,您还可以将构造函数实现替换为:

CVector(Eigen::Index size1) : Base_Vector(size1) {}
CVector(Eigen::Index size1, T val)
    : Base_Vector(Base_Vector::Constant(size1, val) { }
CVector(T const * val_array, Eigen::Index val_array_size)
    : Base_Vector(Base_Vector::Map(val_array, val_array_size) { }

顺便说一句:不知道,为什么CVector&lt;float&gt; v3(tab, 5); 没有发出与int 变体相同的警告...

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多