gpt4 book ai didi

c++ - 检查类型是否为 Eigen3 类型

转载 作者:行者123 更新时间:2023-12-02 10:08:52 24 4
gpt4 key购买 nike

Eigen3 和内置类型互兼容

大家好。我遇到了编写可以处理 Eigen3 类型(矩阵和数组)和内置类型的例程的问题。我可以用一个例子来最好地解释这一点:假设我有一个 Meter<Type>具有在运行时收集统计信息的能力的模板类。

Type 类应支持以下运算符:

  • operator=(Scalar)
  • operator=(Type)
  • operator+(Type)
  • operator-(Type)
  • operator*(Type)
  • operator/(Type)
  • operator*(Scalar)
  • operator/(Scalar)
  • Eigen3 types 提供了所有这些运算符,但有两个异常(exception):首先, operator*(Type)如果 Type 表示点积是 Eigen::MatrixBase 的某个子类如果 Type 则表示系数乘积是 Eigen::ArrayBase 的某个子类.我可以很容易地解决这个问题;其次,没有人实现 operator=(Scalar)需要确保正确初始化为零。

    我尝试实现以下仿函数类来帮助我处理区别,但我无法让它们工作:

    一些结构来处理内置类型和 Eigen3 之间的区别类型:
    template < class _Type > struct is_scalar : true_type {
    using Scalar = _Type;
    using Type = _Type;

    static constexpr bool value = true;
    };

    template < class _Matrix >
    struct is_scalar<Eigen::MatrixBase<_Matrix>> : false_type {
    using Scalar = typename Matrix::Scalar;
    static constexpr bool value = false;
    };

    template < class _Array >
    struct is_scalar<Eigen::ArrayBase<_Array>> : false_type {
    using Scalar = typename Array::Scalar;
    static constexpr bool value = false;
    };

    函数实现本身
    template < class Scalar, bool is_scalar = Math::is_scalar<Scalar>::value > 
    struct set_const_impl;

    template < class Scalar >
    struct set_const_impl< Scalar, true > {
    static const void run(Scalar &_x, Scalar _y) noexcept { _x = _y; }
    };

    template < class EigenType >
    struct set_const_impl<EigenType, false> {
    template < class Scalar >
    static const void run(Eigen::EigenBase<EigenType> &_x, Scalar _y) noexcept {
    _x.derived().setConstant(_y);
    }
    };

    template < class Type, class Scalar > void set_const(Type &_x, Scalar _y) noexcept {
    set_const_impl<Type>::run(_x, _y);
    }

    template < class Type > void set_zero(Type &_x) noexcept {
    set_const_impl<Type>::run(_x, 0);
    }

    专业版 set_const_impl<EigenType>永远不会被实例化。例如,如果我打电话
    Eigen::Matrix<double, 3, 1> m1; 
    set_zero(m1);

    我让编译器向 0 投诉在线上
    set_const_impl<Type>::run(_x, 0);

    0不能隐式转换为 Eigen::Matrix<double, 3, 1> ,这意味着它选择了 set_const_impl<Scalar, true>仿函数的版本(其中两个参数共享一个公共(public)类型 Scalar )。这也意味着我的 is_scalar在这种情况下,构造不起作用,即使我已经使用它并在其他类上测试它没有问题。

    我在其他几个类中需要这种行为,我不想明确地专门化它们中的每一个!任何人都知道我应该怎么做才能解决这个问题?

    提前感谢您的帮助!

    最佳答案

    你的问题是你的特质is_scalar它只接受基类而不接受派生类。

    您可以尝试以下方法:

    namespace Helper
    {
    template <typename T> std::false_type is_scalar(const Eigen::MatrixBase<T>*);
    template <typename T> std::false_type is_scalar(const Eigen::ArrayBase<T>*);
    std::true_type is_scalar(...);
    }

    template<typename T>
    struct is_scalar : decltype(Helper::is_scalar(std::declval<T*>()))
    {};

    关于c++ - 检查类型是否为 Eigen3 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25222804/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com