【问题标题】:Function taking Eigen::Tensor - template argument deduction fails采用 Eigen::Tensor 的函数 - 模板参数推导失败
【发布时间】:2019-04-03 09:24:01
【问题描述】:

我正在尝试编写一个以Eigen::Tensor 作为参数的模板函数。适用于Eigen::Matrix 等的相同方法在这里不起作用。

Eigen 建议使用通用基类编写函数。 https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html

编译的Eigen::Matrix 的最小示例:

#include <Eigen/Dense>

template <typename Derived>
void func(Eigen::MatrixBase<Derived>& a) 
{
    a *= 2;
}

int main()
{
    Eigen::Matrix<int, 2, 2> matrix;
    func(matrix);
}

以及无法编译Eigen::Tensor的最小示例:

#include <unsupported/Eigen/CXX11/Tensor>

template <typename Derived>
void func(Eigen::TensorBase<Derived>& a)
{
    a *= 2;
}

int main()
{
    Eigen::Tensor<int, 1> tensor;
    func(tensor);
}
$ g++ -std=c++11 -I /usr/include/eigen3 eigen_tensor_func.cpp
eigen_tensor_func.cpp: In function ‘int main()’:
eigen_tensor_func.cpp:12:16: error: no matching function for call to ‘func(Eigen::Tensor<int, 1>&)’
     func(tensor);
                ^
eigen_tensor_func.cpp:4:6: note: candidate: ‘template<class Derived> void func(Eigen::TensorBase<Derived>&)’
 void func(Eigen::TensorBase<Derived>& a)
      ^~~~
eigen_tensor_func.cpp:4:6: note:   template argument deduction/substitution failed:
eigen_tensor_func.cpp:12:16: note:   ‘Eigen::TensorBase<Derived>’ is an ambiguous base class of ‘Eigen::Tensor<int, 1>’
     func(tensor);

【问题讨论】:

    标签: c++ templates tensor eigen3


    【解决方案1】:

    Tensor-Module 离完全兼容 Eigen/Core 功能还很遥远(当然,这也意味着核心功能的文档不一定适用于 Tensor-Module)。

    第一个主要区别是TensorBase 采用两个模板参数而不是一个,即您需要编写TensorBase&lt;Derived, Eigen::WriteAccessors&gt;。还有一些功能根本没有实现,或者TensorBase 没有正确转发它。以下适用于当前主干(2019-04-03):

    template <typename Derived>
    void func(Eigen::TensorBase<Derived, Eigen::WriteAccessors>& a)
    {
        // a *= 2;  // operator*=(Scalar) not implemented
        // a = 2*a; // operator=(...) not implemented/forwarded
        a *= a;     // ok
        a *= 2*a;   // ok
        a *= 0*a+2; // ok
    
        // a.derived() = 2*a; // derived() is not public
        static_cast<Derived&>(a) = a*2; // ok
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 2020-06-05
      相关资源
      最近更新 更多