gpt4 book ai didi

c++ - 整数序列作为非类型模板参数

转载 作者:行者123 更新时间:2023-12-02 01:31:40 25 4
gpt4 key购买 nike

我想将几个任意长度的整数序列作为非类型参数传递给模板类,因此实例化将如下所示:

Foo<Bar, {1,2,3,4}, {5,6,7}> foo;

有没有一种简单的方法可以做到这一点,可以使用 C++11 吗?

*** 编辑好的,这是更具体的情况:

#include <vector>
using std::vector;

void f(vector<int> const & vec1, vector<int> const & vec2) {
// do something with vec1 and vec2
}

template<MagicalSequenceType & seq1, MagicalSequenceType & seq2>
struct Foo {
Foo(){
f(vector<int>(seq1), vector<int>(seq2));
}
};

main(){
// I want to be able to do something like this:
// ideally with syntax this elegant but not necessary
Foo < {1,2,3,4}, {5,6,7} > foo;
}

这有点伪代码级别。我想 MagicalSequenceType 就是我想要的,无论是实际类型还是一些语法模板技巧:)

最佳答案

这里是一个关于如何在c++11中使用任意长度整数序列作为模板参数的示例。正如我们所见,它需要一些模板魔法:P

#include <array>
#include <utility>
#include <iostream>

// Crude c++14 integer_sequence
template<int...>
struct ints { };

// Turn an integer sequence into a std::array
template<int... Is>
constexpr std::array<int, sizeof...(Is)>
ints_to_array(ints<Is...>)
{
return std::array<int, sizeof...(Is)>{Is...};
}

// Get the n'th sequence from a template parameter pack
template<std::size_t Idx, class First, class... Sequences>
struct get_n
{
static_assert(Idx < sizeof...(Sequences) + 1, "Idx must be in range");
using type = typename get_n<Idx - 1, Sequences...>::type;
};

template<class First, class... Sequence>
struct get_n<0, First, Sequence...>
{
using type = First;
};

struct Bar { };

// The class needing multiple integer sequences
template<class T, class... Sequences>
struct Foo
{
void function_using_second_sequence()
{
using sequence = typename get_n<1, Sequences...>::type;
constexpr auto vals = ints_to_array(sequence());
for (auto i : vals) {
std::cout << i << " ";
}
std::cout << '\n';
}
};

int main()
{
Foo<Bar, ints<1, 2, 3, 4>, ints<5, 6, 7>> foo;
foo.function_using_second_sequence();
}

试试 godbolt

编辑:在c++20中它要简单得多:P

#include <array>
#include <iostream>
#include <utility>

template<std::size_t Idx, class First, class... Args>
constexpr decltype(auto)
get_n(First&& first, Args&& ...args)
{
if constexpr (Idx == 0)
return std::forward<First>(first);
else
return get_n<Idx - 1>(std::forward<Args>(args)...);
}

template<class T, auto... Sequences>
struct Foo
{
void function_using_second_sequence()
{
constexpr auto vals = get_n<1>(Sequences...);
for (auto i : vals) {
std::cout << i << " ";
}
std::cout << '\n';
}
};

struct Bar { };

int main()
{
Foo<Bar, std::array{1, 2, 3, 4}, std::array{5, 6, 7}> foo;
foo.function_using_second_sequence();
}

关于c++ - 整数序列作为非类型模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73166509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com