如何使用模板创建多维 std::array?

编程入门 行业动态 更新时间:2024-10-16 00:18:46
本文介绍了如何使用模板创建多维 std::array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如何创建具有(当然)已知初始 constexpr 维度和一些智能的 Type 类型的多维 std::array可变参数模板MDA".

How can I create a multi dimensional std::array of type Type with (of course) known initial constexpr dimensions with some smart variadic template "MDA".

维数应可变.

最后我希望能够写:

MDA<int,3,4,5,6> a4d{};

结果应该等于

std::array < std::array < std::array < std::array<int, 6> , 5 > , 4 > , 3 > a4d{};

并节省大量(复杂的,甚至容易出错的)打字工作...

And save a lot of (complicated, or even error prone) typing work . . .

我不确定这是否可能.但我正在寻找的是一些打字保护程序",可能与 using 语句结合使用.

I am not sure if this possible at all. But what I am looking for, is some "typing saver", maybe in conjunction with a using statement.

推荐答案

当然可以使用辅助类模板,C++11(静态断言部分除外)

Certainly possible with use of helper class templates, C++11 (except the static assert part)

#include <array>

template<typename T, std::size_t Head, std::size_t... Tail>
struct MDA_impl{
    using type = std::array<typename MDA_impl<T, Tail...>::type, Head>;
};
// Base specialization
template<typename T, std::size_t N>
struct MDA_impl<T,N>{
    using type = std::array<T, N>;
};

template<typename T, std::size_t... Ns>
using MDA = typename MDA_impl<T,Ns...>::type;

int main(){
    static_assert(std::is_same_v<MDA<int,3,4,5,6>,
                  std::array<std::array<std::array<std::array<int, 6>,5>,4>,3>>);
}

这篇关于如何使用模板创建多维 std::array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 06:06:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405482.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   如何使用   模板   array   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!