c++ - 将 VT 解包与元序列交织在一起

标签 c++ variadic-templates

template <int I> struct int_ {};

template < typename ... Pack >
struct thingy
{
    void call()
    {
       f(???);
    }
 };

实例化后应该是:

struct thingy<int,char,double>
{
    void call()
    {
        f(int, int_<1>(), char, int_<2>(), double, int_<3>());
    }
}

你怎么想,能做到吗?怎么办?

我唯一能想到的就是对具有 N 个不同参数的事物进行重载,如下所示:

template < typename T0 > struct thingy<T0> { ... };
template < typename T0, typename T1 > struct thingy<T0,T1> { ... };

etc...

每个都有一个调用实现。

最佳答案

Can it be done

当然可以。

How ?

分几个步骤。

  • 你需要能够创建一个整数范围
  • 你需要能够交错两个序列

让我们从整数范围开始。

template <size_t...>
struct IntegralPack {};

template <size_t A, size_t... N>
IntegralPack<N..., A> push_back(IntegralPack<N...>);

template <size_t A, size_t... N>
IntegralPack<A, N...> push_front(IntegralPack<N...>);

template <size_t L, size_t H>
struct IntegralRangeImpl {
    typedef typename IntegralRangeImpl<L+1, H>::type Base;
    typedef decltype(push_front<L>((Base()))) type;
};

template <size_t X>
struct IntegralRangeImpl<X, X> {
    typedef IntegralPack<> type;
};

template <size_t L, size_t H>
struct IntegralRange {
     static_assert(L <= H, "Incorrect range");
     typedef typename IntegralRangeImpl<L, H>::type type;
};

转换步骤很简单(谢天谢地):

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

template <size_t... N>
TypePack<int_<N>...> to_int(IntegralPack<N...>);

所以下一个难点就是合并。

template <typename... As, typename... Bs>
TypePack<As..., Bs...> cat(TypePack<As...>, TypePack<Bs...>);

template <typename, typename> struct Interleaver;

template <>
struct Interleaver<TypePack<>, TypePack<>> {
  typedef TypePack<> type;
};

template <typename A0, typename B0, typename... As, typename... Bs>
struct Interleaver<TypePack<A0, As...>, TypePack<B0, Bs...>> {
  typedef typename Interleaver<TypePack<As...>, TypePack<Bs...>>::type Base;
  typedef decltype(cat(TypePack<A0, B0>{}, Base{})) type;
};

总而言之:

template <typename... Pack>
struct thingy {
    typedef typename IntegralRange<1, sizeof...(Pack) + 1>::type Indexes;
    typedef decltype(to_int(Indexes{})) Ints;
    typedef typename Interleaver<TypePack<Pack...>, Ints>::type Types;

    void call() { this->callImpl(Types{}); }

    template <typename... Ts>
    void callImpl(TypePack<Ts...>) {
        f(Ts{}...);
    }
};

该死!

关于c++ - 将 VT 解包与元序列交织在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10527776/

相关文章:

c++ - 如何将 SHA1 转换为无符号长整型数组 [5]?

c++ - 对失败的元组 vector 使用可变参数模板参数

c++ - 可变模板类构造函数

c++ - 模板包包

c++ - 从 C++ 缓冲区中提取 IP 地址(Linux 套接字)

c++ - 如何绕过警告 "rvalue used as lvalue"?

c++ - 用比较器初始化集合

C++ - 如何调用递归继承的模板化基类的模板化方法

c++ - 空包可变参数模板

c++ - 我可以只对一个模板使用 `-fno-implicit-templates` 功能吗?