gpt4 book ai didi

c++ - 如何展平嵌套模板参数?

转载 作者:行者123 更新时间:2023-11-30 00:43:29 24 4
gpt4 key购买 nike

说我有

template<class ... T> pack { };

我要转换

pack<int, pack<int, pack<int, pack<int>>>>

进入

pack<int, int, int, int>

我该怎么做?

最佳答案

我提出以下结构和使用

template <typename T0, typename...>
struct flatt_helper
{ using type = T0; };

template <typename ... Ts1, typename T0, typename ... Ts2>
struct flatt_helper<pack<Ts1...>, T0, Ts2...>
: flatt_helper<pack<Ts1..., T0>, Ts2...>
{ };

template <typename ... Ts1, template <typename ...> class C,
typename ... Ts2, typename ... Ts3>
struct flatt_helper<pack<Ts1...>, C<Ts2...>, Ts3...>
: flatt_helper<pack<Ts1...>, Ts2..., Ts3...>
{ };

template <typename T>
using flatt = typename flatt_helper<pack<>, T>::type;

这样你就可以展平pack和其他模板模板,如std::tuple ,以及更复杂的示例(例如,Holt 建议的 pack<int, pack<int, int>, int>)。

如果你只想要公寓 pack ,避免所有模板模板都被压平......,我的意思是......如果你想要那个

pack<int, pack<int, std::tuple<int, long>>>

被压扁为

pack<int, int, std::tuple<int, long>>

代替

pack<int, int, int, long>

你必须在最后一个 flatt_helper 中删除模板模板参数特化化简如下

template <typename ... Ts1, typename ... Ts2, typename ... Ts3>
struct flatt_helper<pack<Ts1...>, pack<Ts2...>, Ts3...>
: flatt_helper<pack<Ts1...>, Ts2..., Ts3...>
{ };

下面是一个完整的编译示例(完全扁平化)

#include <tuple>
#include <type_traits>

template <typename...>
struct pack
{ };

template <typename T0, typename...>
struct flatt_helper
{ using type = T0; };

template <typename ... Ts1, typename T0, typename ... Ts2>
struct flatt_helper<pack<Ts1...>, T0, Ts2...>
: flatt_helper<pack<Ts1..., T0>, Ts2...>
{ };

template <typename ... Ts1, template <typename ...> class C,
typename ... Ts2, typename ... Ts3>
struct flatt_helper<pack<Ts1...>, C<Ts2...>, Ts3...>
: flatt_helper<pack<Ts1...>, Ts2..., Ts3...>
{ };

template <typename T>
using flatt = typename flatt_helper<pack<>, T>::type;

int main()
{
using T0 = pack<int, pack<int, pack<int, pack<int>>>>;
using T1 = pack<int, int, int, int>;
using T2 = flatt<T0>;
using T3 = pack<int, pack<int, long>, std::tuple<pack<int, char>, long>>;
using T4 = pack<int, int, long, int, char, long>;
using T5 = flatt<T3>;

static_assert( std::is_same<T1, T2>::value, "!" );
static_assert( std::is_same<T4, T5>::value, "!" );
}

关于c++ - 如何展平嵌套模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025813/

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