问题描述
限时送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:关键词]
发布评论