使用 MSVS 避免模板化特征函数中的模糊参数

Avoiding ambiguous parameters in templated Eigen functions with MSVS

我正在编写一些应该将 Eigen::Array 作为输入的函数。 数组的大小不变,但大小是模板参数,应从输入中扣除。 使用 MSVS 编译时,我必须为函数提供大小,否则会导致错误。

#include <Eigen/Core>

template<unsigned short t_iSize>
void foo(const Eigen::Array<unsigned short, t_iSize, 1>&)
{

}

int main()
{
    Eigen::Array<unsigned short, 3, 1> test;
    // foo(test);    // Compiler errors C2672 and C2784
    foo<3>(test);    // Giving the size solves the errors
}

应该可以从变量中扣除大小test,但在计算数组的模板参数 4 和 5 时似乎失败了。

Error C2672: "foo": no matching overloaded function found.

Error C2784: "void foo(const Eigen::Array< unsigned short,t_iSize,1,|_Rows==&&?:&&_Rows!=?:,_Rows,1> &)": could not deduce template argument for "const Eigen::Array< unsigned short,t_iSize,1,|_Rows==&&?:&&_Rows!=?:,_Rows,1> &" from "Eigen::Array< unsigned short,3,1,0,3,1>".

带Eigen::Array是否可以避免这个问题,还是需要把Eigen::ArrayBase作为函数参数?我想避免这种情况,因为它掩盖了函数只接受这种特定类型数组的事实。

编辑:

正如 Jarod42 指出的那样,模板参数应该是 int 类型。 Visual Studio 可以编译有这个错误的代码。 但是,它无法推导参数 _Rows,而其他编译器可以这样做。

Here你可以看到我运行的问题。

Eigen::Array 的声明是

template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
class Eigen::Array;

您的函数使用了错误的行类型,unsigned short 应该是 int

template <int t_iSize>
void foo(const Eigen::Array<unsigned short, t_iSize, 1>&)
{
    // ...
}

Demo

作为 Msvc 问题的解决方法,您可以这样做:

  • 手动应用默认值:

    template <int t_iSize>
    void bar(const Eigen::Array<unsigned short, t_iSize, 1, 0, t_iSize, 1>&) {
      // ...
    }
    
  • 或添加额外的模板(因此代码更加通用):

    template <int t_iSize, int Options, int MaxRows, int MaxCols>
    void foo(const Eigen::Array<unsigned short, t_iSize, 1, Options, MaxRows, MaxCols>&) {
      // ...
    }
    

Demo