简体   繁体   中英

ambiguity of overloaded function taking constant Eigen argument

I've designed a class with two overloaded functions taking Eigen data structures of different sizes.

The code compiles as long as I'm passing lvalues but if I pass an rvalue I get a compiler error ambiguity because both return the same ConstantReturnType .

Here is a MWE:

#include <iostream>
#include <Eigen/Geometry>

using namespace std;
using namespace Eigen;


class MyOverloadAmbiguity {
public:
  void ambiguousOverload(const Eigen::Vector3d& v) {
    std::cout << "I'm taking a Vector3d\n";
  }
  void ambiguousOverload(const Eigen::Vector4d& v){
    std::cout << "I'm taking a Vector4d\n";
  }
};


int main()
{
  MyOverloadAmbiguity moa;
  Eigen::Vector3d v3;

  moa.ambiguousOverload(v3); // <--- this works
  moa.ambiguousOverload(Eigen::Vector4d::Zero()); // <--- this doesn't

  return 0;
}
main.cpp:26: error: call of overloaded ‘ambiguousOverload(const ConstantReturnType)’ is ambiguous
   26 |   moa.ambiguousOverload(Eigen::Vector4d::Zero());
      |                                                ^
    main.cpp:10:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector3d&)’
   10 |   void ambiguousOverload(const Eigen::Vector3d& v) {
      |        ^~~~~~~~~~~~~~~~~
main.cpp:13:8: note: candidate: ‘void MyOverloadAmbiguity::ambiguousOverload(const Vector4d&)’
   13 |   void ambiguousOverload(const Eigen::Vector4d& v){
      |        ^~~~~~~~~~~~~~~~~

Is there a way to avoid this without explicitly changing the function names or add extra arguments just to avoid the ambiguity?

Your example does not work because the return type of Zero() is not a matrix, but an Eigen expression.

Thus, one way of achieving what you want with minimal changes is to use explicit matrix evaluation:

moa.ambiguousOverload(Eigen::Vector4d::Zero().eval());

You may also want to consider writing functions taking Eigen expressions as parameters (rather than explicit matrices), as an alternative solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM