You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从模板化向量类中获取维度dim参数值

问题解决:实现Vec<N>::dim获取向量维度

错误原因

你定义的Vec只是Eigen::Matrix的类型别名,而Eigen矩阵类本身并没有名为dim的静态成员,因此vec_t::dim会触发编译错误。要实现Vec2d::dim这类用法,需要给你的向量类型显式添加维度成员。

解决方案

把Vec从类型别名改为继承自Eigen::Matrix的结构体,在结构体中添加静态维度成员(或枚举),这样就能直接通过Vec<N>::dim访问维度值。

修改后的完整代码

#include <Eigen/Core>
#include <cstdio>

namespace MyNamespace {
    template <class scalar_t, int dim>
    struct Vec : public Eigen::Matrix<scalar_t, dim, 1, Eigen::ColMajor | Eigen::AutoAlign, dim, 1> {
        // 继承Eigen矩阵的所有构造函数
        using Base = Eigen::Matrix<scalar_t, dim, 1, Eigen::ColMajor | Eigen::AutoAlign, dim, 1>;
        using Base::Base;

        // 定义静态维度成员,与模板参数dim一致
        static constexpr int dim = dim;
        // 也可以用枚举匹配你原本的写法:
        // enum { dim = dim };
    };

    using Vec1d = Vec<double, 1>;
    using Vec2d = Vec<double, 2>;
    using Vec3d = Vec<double, 3>;
    using Vec4d = Vec<double, 4>;
}

namespace MyNamespace {
/**
 * A class representing Monomial basis.
 */
template <typename vec_t>
class Monomials {
  public:
    typedef vec_t vector_t;   ///< Vector type.
    /// Store dimension of the domain.
    enum { /** Dimensionality of the domain. */ dim = vec_t::dim };

  public:
    /**
     * Construct a basis of all monomials
    */
    Monomials(int order){
        printf("order: %d\n", order);
        printf("dimension: %d\n", vec_t::dim);
    };
};
}

using namespace MyNamespace;    

int main(){
    auto p = Vec2d{0.0, 1.0};

    printf("%f, %f\n", p[0], p[1]);
    // 直接测试Vec2d::dim
    printf("Vec2d dimension: %d\n", Vec2d::dim);
    auto m = Monomials<Vec2d>(2);

    return 0;
}

其他可选方案(无需修改Vec定义)

如果不想改动Vec的别名定义,可以通过类型萃取提取维度:

namespace MyNamespace {
    template <typename T>
    struct VecDimTraits;

    // 针对你的Vec别名特化萃取类
    template <class scalar_t, int dim>
    struct VecDimTraits<Vec<scalar_t, dim>> {
        static constexpr int value = dim;
    };

    // 通用适配Eigen矩阵(你的Vec是列向量,行数即为维度)
    template <typename EigenMatrix>
    struct EigenDimTraits {
        static constexpr int value = EigenMatrix::RowsAtCompileTime;
    };
}

随后在Monomials中使用:

enum { dim = VecDimTraits<vec_t>::value };
// 或者
printf("dimension: %d\n", EigenDimTraits<vec_t>::value);

内容的提问来源于stack exchange,提问作者skrat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 08:25:05