如何在使用模板的函数调用的大括号表达式中推导多维数组的大小
how to deduce the size of a multidimensional array in a curly brace expression of a function call with templates
我目前正在编写一个启用类型安全编译时间的张量类,它可以归结为
template<typename T, int... Sizes>
struct tensor {
T elements[(Sizes * ...)];
auto ptr() {return elements;}
auto size() {return (Sizes * ...);}
using value_type = T;
};
我想写一个方法,允许创建一个以数组为表达式的张量,比如:
make_tensor({1,2,3,4})
或make_tensor({{1,2},{3,4}})
,给出一个向量和一个矩阵。我的make_tensor
函数当前如下所示:
template<template<typename, int...> class Fill, typename Type, int... Sizes>
struct array_to_index {
using type = Fill<Type, Sizes...>;
};
template<template<typename, int...> class Fill, typename Type, int Size, int... Sizes>
struct array_to_index<Fill, Type[Size], Sizes...> {
using type = typename array_to_index<Fill, Type, Sizes..., Size>::type;
};
template<template<typename, int...> class Fill, typename Type>
using array_to_index_t = typename array_to_index<Fill, Type>::type;
template<typename Type, int Size>
auto make_tensor(const Type (&arr)[Size]) {
using tensor_t = array_to_index_t<tensor, Type[Size]>;
tensor_t tensor;
using ptr_t = const typename tensor_t::value_type *;
for(int i = 0; i < tensor.size(); ++i)
tensor.elements[i] = reinterpret_cast<ptr_t>(arr)[i];
return tensor;
}
如果我先分配它,我可以用多维数组调用它,但好的语法不起作用:
int main() {
//auto matrix = make_tensor({{0,1},{2,3},{4,5}}); // doesn't work
int arr[][2] = {{0,1},{2,3},{4,5}};
auto other = make_tensor(arr); // works
assert(other.elements[3] == 3);
}
根据我从这个多维数组初始化器中推导边界失败的问题中收集到的信息,我的方法将不起作用。有没有其他方法可以进行这种推导(例如使用初始值设定项列表(?
不能从嵌套的{{}}
推导多维数组边界。
你可以通过添加一些标记来推断它。
using namespace std;
auto arr = array{ array{1,2}, array{3,4} };
for (auto row : arr) {
for (auto e : row) {
std::cout << e << ",";
}
std::cout << "n";
}
活生生的例子。
array
推导指南撕开下面的{}
表达式,并推导出array
模板的类型。
因此:
make_tensor(a{a{1,2},a{3,4}})
是可能的,甚至
tensor{ tensor{1,2}, tensor{1,2} }
因为CCD_ 8函数是位传递函数。
相关文章:
- 在函数中使用 const int size 参数创建数组会在 Visual Studio 中抛出错误 C++:表达式的计
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 为什么不能用常量表达式声明数组?
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 如何在使用模板的函数调用的大括号表达式中推导多维数组的大小
- 表达式必须具有常数值,变量不能用作定义数组大小的常数
- C++ 使用变量而不是常量表达式初始化数组
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"
- C++:新表达式中的数组大小必须是常量
- 将编译时定义大小的数组初始化为常量表达式
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 循环赋值的多维数组:表达式必须是可修改的左值
- 无法从数组二次表达式中检索数据值
- 数组声明中的错误:表达式必须具有常量值
- 在数组上调用长度时,表达式必须具有类类型
- 错误:数组大小表达式必须具有整型或无作用域枚举类型,而不是'double'
- 如何消除"仅使用常量表达式索引到数组"警告?
- 在 int 数组的情况下,新表达式可以"overflow"吗?
- 使用多线程处理对象数组 - 无效使用 void 表达式错误
- 使用表达式模板编译时间数组索引--constexpr