我正在尝试解决 Eigen 的一些问题。在此过程中,我发现 static_cast 和用户定义的转换可能是 std :: enable_if 引起的问题?
基本上是我尝试过的:
#include <Eigen/Dense>
#include <bits/stdc++.h>
using namespace std;
class Vector2
{
public:
operator Eigen::Vector2d ()
{
return data;
}
private:
Eigen::Vector2d data;
};
class Box2
{
public:
void Extend(const Vector2 & a)
{
data.extend( static_cast<Eigen::Vector2d>(a) ); // error, but why?
}
private:
Eigen::AlignedBox2d data;
};
int main()
{
Vector2 a;
Eigen::Vector2d b = a; // ok, implicit conversion
return 0;
}
g++ -std=c++11
输出许多错误日志,这是最后一部分:
eigen/eigen/Eigen/src/Core/PlainObjectBase.h:863:30: note: template argument deduction/substitution failed:
eigen/eigen/Eigen/src/Core/PlainObjectBase.h: In substitution of ‘template<class T> void Eigen::PlainObjectBase<Derived>::_init1(const Index&, typename Eigen::internal::enable_if<((((((! Eigen::internal::is_same<long int, typename Eigen::internal::traits<T>::Scalar>::value) && Eigen::internal::is_same<long int, T>::value) && (typename Eigen::internal::dense_xpr_base<Derived>::type:: SizeAtCompileTime != Eigen::Dynamic)) && (typename Eigen::internal::dense_xpr_base<Derived>::type:: SizeAtCompileTime != 1)) && Eigen::internal::is_convertible<T, typename Eigen::internal::traits<T>::Scalar>::value) && Eigen::internal::is_same<typename Eigen::internal::traits<T>::XprKind, Eigen::ArrayXpr>::value), T*>::type*) [with T = T; Derived = Eigen::Matrix<double, 2, 1>] [with T = Vector2]’:
eigen/eigen/Eigen/src/Core/Matrix.h:296:33: required from ‘Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::Matrix(const T&) [with T = Vector2; _Scalar = double; int _Rows = 2; int _Cols = 1; int _Options = 0; int _MaxRows = 2; int _MaxCols = 1]’
test.cpp:21:52: required from here
eigen/eigen/Eigen/src/Core/PlainObjectBase.h:863:30: error: invalid use of incomplete type ‘struct Eigen::internal::enable_if<false, Vector2*>’
In file included from eigen/eigen/Eigen/Core:364:0,
from eigen/eigen/Eigen/Dense:1,
from eigen/eigen/Eigen/Eigen:1,
from test.cpp:2:
eigen/eigen/Eigen/src/Core/util/Meta.h:162:50: error: declaration of ‘struct Eigen::internal::enable_if<false, Vector2*>’
template<bool Condition, typename T=void> struct enable_if;
^
似乎是 enable_if 的问题,我想知道为什么 static_cast 不起作用。有没有解决此问题的方法,而无需修改本征?现在可以这样做:
void Extend(Vector2 a)
{
Eigen::Vector2d b = a;
data.extend( b );
}
但这太丑了。
答案 0 :(得分:4)
似乎是
enable_if
的问题,我想知道为什么static_cast
没有 工作。
这与static_cast
本身无关。由于未为Vector2
对象定义operator Eigen::Vector2d ()
的{{1}},并且由于您的const
接受了Box2::Extend()
,因此不会产生适当的转换,因此会产生错误在代码中为该行定义。向const Vector2& a
添加const
的用户定义的转换的Vector2
版本,以使其编译并保留代码的const-correctness:< / p>
Eigen::Vector2d
现在,用法可以按您希望的方式工作:
const operator Eigen::Vector2d () const
{
return data;
}