vso*_*tco 0 c++ initializer-list eigen c++11
我对以下代码感到困惑:
#include <Eigen/Dense>
#include <vector>
class Foo {};
void f(Eigen::MatrixXd const &) {}
void f(std::vector<Eigen::MatrixXd> const &) {}
void g(Foo const &) {}
void g(std::vector<Foo> const &) {}
int main()
{
Foo a, b, c;
Eigen::MatrixXd x, y, z;
// f({x, y}); ambiguity, why?!
f({x, y, z}); // ok
g({a,b}); // ok
g({a,b,c}); // ok
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释中的第 3 行代码main(),我会收到一个模棱两可的调用错误,
/Users/vlad/so.cpp: In function 'int main()':
/Users/vlad/so.cpp:17:13: error: call of overloaded 'f(<brace-enclosed initializer list>)' is ambiguous
f({x, y}); //ambiguity, why?!
^
/Users/vlad/so.cpp:17:13: note: candidates are:
/Users/vlad/so.cpp:6:6: note: void f(const MatrixXd&)
void f(Eigen::MatrixXd const &) {}
^
/Users/vlad/so.cpp:7:6: note: void f(const std::vector<Eigen::Matrix<double, -1, -1> >&)
void f(std::vector<Eigen::MatrixXd> const &) {}
Run Code Online (Sandbox Code Playgroud)
使用 init 列表中的 3 个项目调用它是有效的。
但是,如果我不使用特征矩阵,而是使用自己的类Foo(请参阅函数g),则一切正常。我完全不知道为什么在使用 Eigen 时注释行是模棱两可的。有任何想法吗?
PS:如果我超载f以至于它需要一个std::initializer_list<Eigen::MatrixXd>,那么问题就会消失,不再有模棱两可的调用。
错误很可能是由这个构造函数模板引起的。
template<typename T0, typename T1>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Matrix(const T0& x, const T1& y)
{ ... }
Run Code Online (Sandbox Code Playgroud)
该构造函数和vector的initializer_list构造函数在函数调用中同样匹配良好f({x, y});,从而导致歧义错误。
这是一个带有类似构造函数和函数调用的虚构示例,也会导致歧义错误。