Eigen 类型的模糊调用

问题描述 投票:0回答:1

试图创建一个同时采用

Eigen::Matrix3d
Eigen::Vector4d
作为构造函数参数的类,但遇到了歧义问题。给定以下测试类,

class MyClass
{
  public:
   MyClass(const Eigen::Matrix3d& m)
    {
    }

    MyClass(const Eigen::Vector4d& v)
    {
    }
};

如果我执行以下操作,

int main(int argc, char** argv)
{
    Matrix3d m;
    MyClass t1(m.transpose());
}

编译失败,出现以下错误,

call of overloaded ‘MyClass(Eigen::Transpose<Eigen::Matrix<double, 3, 3> >)’ is ambiguous
  516 |     MyClass t1(m.transpose());
      |                             ^
note: candidate: ‘MyClass::MyClass(const Vector4d&)’
  561 |     MyClass(const Eigen::Vector4d& v)
      |     ^~~~~~~
note: candidate: ‘MyClass::MyClass(const Matrix3d&)’
  556 |     MyClass(const Eigen::Matrix3d& m)

我不清楚如何解决这个问题

c++ c++17 eigen3 ambiguous
1个回答
1
投票

您可以创建构造函数模板来接受

Eigen::Transpose<...>
对象(由
transpose()
返回)和具体的
Matrix3d
Matrix4d
对象。

我假设您的两个独立构造函数中的操作非常相似,因此您可以将它们组合起来:

class MyClass {
public:
    // One constructor template accepting both Matrix3d and Matrix4d:
    template<class Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
    MyClass(const Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>& m)
    {
        // here you can do what you did in the two separate constructors before
        std::cout << Rows << ',' << Cols << '\n';
    }

...并为

Transpose
对象添加委托构造函数模板:

    // delegating constructor taking an Eigen::Transpose object:
    template<class Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
    MyClass(const Eigen::Transpose<
            Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>>& t) :
        // delegate to the constructor shown above:
        MyClass(Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>(t))
    {
        std::cout << "(was delegated)\n";
    }
};

现在以下所有情况都有效:

int main() {
    Eigen::Matrix3d m3;
    Eigen::Matrix4d m4;

    MyClass t3(m3);              // no delegation
    MyClass t4(m4);              // no delegation
    MyClass t3t(m3.transpose()); // delegating
    MyClass t4t(m4.transpose()); // delegating
}

输出:

3,3
4,4
3,3
(was delegated)
4,4
(was delegated)

如果你 only 想接受换位,删除第一个构造函数和委托:

class MyClass {
public:
    template<class Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
    MyClass(const Eigen::Transpose<
            Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>>& t)
    {
        Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols> m(t);
        // use `m` here
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.