我正在编写一个库,该库具有以无符号整数为模板的编译时多态对象,
template<unsigned level> class Foo { ... };
,即 Foo<0>、Foo<1>、Foo<2> 等,最多为每个应用程序确定的特定数量。假设我们的应用程序指定需要数字 0、1、...、n。
我需要能够构造指向这些对象的指针 vector 元组:std::tuple<std::vector<Foo<n> *>, std::vector<Foo<n-1> *>, ..., vector<Foo<0> *>>
通过调用可变参数模板函数,示意性地:
template <unsigned n>
std::tuple<unsigned n, unsigned... Args> create_vector_tuple<n>()
或者类似的东西。
我的直觉告诉我,这应该是可以实现的,尽管我的能力远远超出了我的能力范围。
如果有人能指出我实现此目的的方法,我将非常感激!
最佳答案
类似于以下内容:
#include <cstdio>
#include <tuple>
#include <vector>
#include <utility>
template<unsigned level> struct Foo {};
template<unsigned N, unsigned... Ns>
std::tuple<std::vector<Foo<N - Ns>*>...> create_vector_tuple_imp(std::integer_sequence<unsigned, Ns...>) {
return {};
}
template <unsigned n>
auto create_vector_tuple() {
return create_vector_tuple_imp<n>(std::make_integer_sequence<unsigned, n>{});
}
template<class T>
void print() {
std::printf("%s\n", __PRETTY_FUNCTION__);
}
int main() {
auto t = create_vector_tuple<10>();
print<decltype(t)>();
}
输出:
void print() [with T = std::tuple<std::vector<Foo<10u>*, std::allocator<Foo<10u>*> >, std::vector<Foo<9u>*, std::allocator<Foo<9u>*> >, std::vector<Foo<8u>*, std::allocator<Foo<8u>*> >, std::vector<Foo<7u>*, std::allocator<Foo<7u>*> >, std::vector<Foo<6u>*, std::allocator<Foo<6u>*> >, std::vector<Foo<5u>*, std::allocator<Foo<5u>*> >, std::vector<Foo<4u>*, std::allocator<Foo<4u>*> >, std::vector<Foo<3u>*, std::allocator<Foo<3u>*> >, std::vector<Foo<2u>*, std::allocator<Foo<2u>*> >, std::vector<Foo<1u>*, std::allocator<Foo<1u>*> > >]
关于C++:基于积分模板参数创建可变长度元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286051/