问题描述
我试图用C ++(11/14)实现fortran的 reshape
函数,并设计了一个函数。此函数接受两个 std :: initializer_list
。第一个 initializer_list
给出了一些初始值,这些值用于初始化 D
维数组。第二个 initializer_list
给出数组每个维度的大小。
我写了这样的草稿
I am trying to implement the reshape
function of fortran with C++(11/14) and I designed a function. This function accepts two std::initializer_list
. The first initializer_list
gives initial values which I use to initialize a D
-dimensional array. The second initializer_list
gives size of each dimension of the array.I wrote a draft like this
template<int D, typename T>
auto forreshape(const std::initializer_list<T> & values, const std::initializer_list<int> & shape)
{
// some irrelevant codes to calculate lbound
return for1array_gen<T, D>(lbound, shape, values); // returns D dimension array fornarray<T, D>
}
int main(){
auto reshaped_array = forreshape<2>({1, 2, 3, 4, 5, 6}, {2, 3});
}
此实现需要给定的非类型模板参数 int D
,但我想要没有 D
的东西,例如 forreshape({1、2、3、4、5、6} ,{2,3});
。
首先,我想使用 std :: initializer_list< T> :: size
,但是来自我知道它不起作用。环顾四周,我发现,但这对我的情况没有帮助。
我以为编译器可以自动获取足够的信息并推断出 int D
的值,但我不知道该怎么做。使用 std :: initializer_list
可能不是一个好主意吗?我在这里完全迷路了
This implementation requires given non type template parameter int D
, but I want something without D
, like forreshape({1, 2, 3, 4, 5, 6}, {2, 3});
.At first I want to use std::initializer_list<T>::size
, however from static-assert-on-initializer-listsize I know it doesn't work. Looking around I found how-to-cause-a-compile-time-error-based-on-the-size-of-an-initializer-list but it didn't help to my case.I thought the compiler can get enough infomation and deduce value of int D
automaticlly, but I don't know how. Maybe its a bad idea to use std::initializer_list
? I got totally lost here
推荐答案
我想是的。考虑
std::initializer_list<int> t;
std::initializer_list<int> a = {1,2,3};
std::initializer_list<int> b = {2,3};
if (rand() > 42)
t = a;
else
t = b;
auto reshaped_array = forreshape({1,2,3,4,5,6}, t);
在上面的示例中,完全不可能知道 t.size()
在编译时。
In the above example, it's just impossible to know t.size()
at compile time.
但是您可以要求编译器使用对C样式数组的引用来推断初始化列表的长度,感谢。
But you can ask the compiler to deduce the length of an initializer list by using a reference to C-style array, thanks to CWG 1591.
forshape
看起来像是:
template<int D, typename T>
auto forreshape(const std::initializer_list<T> & values, const int (&shape)[D])
{
// use D...
}
这篇关于在编译时获取`std :: initializer_list`的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!