【问题标题】:C++ templated alias of N-dimensional vectorN维向量的C++模板别名
【发布时间】:2019-12-27 02:25:44
【问题描述】:

我想要一些简单的 N 维向量包装器,例如 vector<vector<vector<double>>> 等。更准确地说,我想在我的代码中编写 NDvector<3,double> 之类的东西,而不是 vector<vector<vector<double>>>。实现这一点的最优雅的方式是什么?我的想法是写类似

template<size_t N, typename T>
using NDvector = vector<NDvector<N-1, T>>;

template<typename T>
using NDvector<1,T> = vector<T>;

但是,这个不能编译。

【问题讨论】:

    标签: c++ templates vector


    【解决方案1】:

    Type alias 不能偏特化;

    不能partiallyexplicitly specialize 别名模板。

    您可以添加一个可以部分专门化的类模板。例如

    template<size_t N, typename T>
    struct NDvector_S {
        using type = vector<typename NDvector_S<N-1, T>::type>;
    };
    template<typename T>
    struct NDvector_S<1, T> {
        using type = vector<T>;
    };
    
    template<size_t N, typename T>
    using NDvector = typename NDvector_S<N, T>::type;
    

    那么你就可以把它当做

    NDvector<3, double> v3d; // => std::vector<std::vector<std::vector<double>>>
    

    【讨论】:

    • 也许,没有我希望在理想世界中看到的那么优雅,但工作得非常好!
    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2017-09-02
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多