有没有一种方法来存储任何(但常量)长度的std ::数组的集合,其中的数组长度可以稍后在constexpr中使用?存储任何(但常量)长度的std ::数组的集合
我猜标准容器没有问题,但可能有某种模板解决方案。所有的信息都可以在编译时使用,不是吗?
示例代码:
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <algorithm>
// Class storing an array of any (but constant) size
struct A {
const std::vector<std::string> container;
const int container_size;
A(const std::vector<std::string>& v, int size) : container(v), container_size(size) { }
};
int main() {
// List of variable length const arrays and their sizes
std::vector<A> myAList {
A({ std::string("String1"), std::string("String2") }, 2),
A({ std::string("String1") }, 1)
};
// How would I go about using the size of each array in a constexpr?
for (auto const& a : myAList) {
// Example constexpr:
// somefunc(std::make_index_sequence<a.container_size>{});
// 2nd example converting to actual std::array
// std::array<std::string, a.container_size> arr;
// std::copy_n(std::make_move_iterator(a.begin()), a.container_size, arr.begin());
}
return 0;
}
更新:被要求
更多细节,所以这里去。我并不关心数组是如何定义的,任何可行的......使用的确切constexpr是示例代码std::make_index_sequence<CONSTEXPR>{}
中的那个。 我只知道我有一组在编译时定义的常量数组,它应该以某种方式在constexpr的其他地方引用它们的长度。
哎呀,其实我是罚款只是存储长度:
// Class storing an array size
struct A {
A(int size) : container_size(size) { }
const int container_size;
};
int main() {
// List of lengths
std::vector<A> mySizeList { 2, 1 };
for (auto const& a : mySizeList) {
// somefunc(std::make_index_sequence<a.container_size>{});
}
return 0;
}
的simpke答案是你不能。更复杂的答案可能归结为“可能,取决于确切的constexpr操作,以及您构建所述数组的方式以及您未包含的其他细节”,并且实现非常棘手。你只打算以这种方式调用一个特定的'somefunc'? – Yakk
@Yakk'somefunc'是一个可变参数模板函数,它将参数应用于通过函数指针调用的函数。我需要一个编译时索引序列来解压参数,因此'make_index_sequence'是必需的。 – Oystein
这是一个肯定还是不肯定? **“你是否只打算以这种方式调用一个特定的'somefunc'?”**我在此承认“是”,并在下面添加了一个答案。它也传递一个'const&'到'vector'以防你也需要。 – Yakk