C++:基于积分模板参数创建可变长度元组

标签 c++ c++14 variadic-templates template-meta-programming

我正在编写一个库,该库具有以无符号整数为模板的编译时多态对象,

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/

相关文章:

c++ - 为什么我们不能在模板特化的开始/中间使用可变参数模板(以及如何模拟)?

c++ - 结构与类的性能

c++ - 对象似乎没有通过C++的引用传递

c++ - 调用可变参数宏的可变参数函数

c++ - 如何找到最大可能的子类(class)

c++ - 为什么clang拒绝可变参数模板 friend 功能

c++ - 函数调用中的运算符 New

c++ - 我应该对只有 2 个项目的列表使用迭代器吗?

c++ - std::vector::shrink_to_fit() 不检查分配器相等性

c++ - 如何在模板元程序中做短路条件?