首页 > 解决方案 > 为什么我不能从 Eigen::Matrix 继承?

问题描述

我有堂课:

template < unsigned N, typename T >
class MY_EXPORT my_point : protected Eigen::Matrix< T, N, 1 >
{
public:
  using vector_type = Eigen::Matrix< T, N, 1 >;

  my_point() : vector_type{ vector_type::Zero() } {}
  using vector_type::vector_type;
};

我的 Linux (GCC) 版本很好。但是,在 Windows (MSVC 15.9.16) 上,我遇到了非常奇怪的错误

c:\include\eigen3\eigen\src\core\densebase.h(482): error C2338: THIS_METHOD_IS_ONLY_FOR_1x1_EXPRESSIONS (compiling source file c:\code\my_point.cxx) [C:\workspace\KwiverWindows\build\vital\vital.vcxproj]
  c:\include\eigen3\eigen\src\core\densebase.h(481): note: while compiling class template member function 'const float &Eigen::DenseBase<Derived>::value(void) const'
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\matrixbase.h(50): note: see reference to class template instantiation 'Eigen::DenseBase<Derived>' being compiled
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\plainobjectbase.h(100): note: see reference to class template instantiation 'Eigen::MatrixBase<Derived>' being compiled
          with
          [
              Derived=Eigen::Matrix<float,4,1,0,4,1>
          ] (compiling source file c:\code\my_point.cxx)
  c:\include\eigen3\eigen\src\core\matrix.h(180): note: see reference to class template instantiation 'Eigen::PlainObjectBase<Eigen::Matrix<float,4,1,0,4,1>>' being compiled (compiling source file c:\code\my_point.cxx)

看起来编译器正在尝试实例化不适当的方法(例如,稍后的错误正在尝试w()为 3 向量实例化)。我究竟做错了什么?(为什么直接使用没有问题Eigen::Matrix?)

是一个现场演示。

标签: c++c++11templateseigen3

解决方案


问题是 Eigen 不使用 SFINAE/enable_if来隐藏“不合适的”成员,它只是依赖于它们永远不会被实例化(如果有人试图使用它们,则使用静态断言)。因此,一个Eigen类——至少Eigen::Matrix——不能被显式实例化。

这可以通过一个简单的例子看出:

#include <Eigen/Core>
template class Eigen::Matrix< double, 3, 1 >;

现场演示

真正的谜团是为什么 GCC 允许显式实例化. Eigen::MatrixMSVC 没有,但似乎 MSVC 可能是正确的,在这里。

短期解决方案是不出口my_point。当然,这要求所有my_point's 方法的定义要么在标头中可见,要么单独导出(而不是尝试导出整个类)。

长期的解决方案是修复 Eigen,以便可以显式实例化其类型:https ://eigen.tuxfamily.org/bz/show_bug.cgi?id=1768 。


推荐阅读