这个占位符生成器如何工作?

时间:2016-06-08 11:19:19

标签: c++ generics

我找到了这个placeholder generator代码,它允许您根据泛型类型模板生成一个int序列。

template<int...> struct int_sequence {};

template<int N, int... Is> struct make_int_sequence
    : make_int_sequence<N-1, N-1, Is...> {};
template<int... Is> struct make_int_sequence<0, Is...>
    : int_sequence<Is...> {};

template<int> // begin with 0 here!
struct placeholder_template
{};

#include <functional>
#include <type_traits>

namespace std
{
    template<int N>
    struct is_placeholder< placeholder_template<N> >
        : integral_constant<int, N+1> // the one is important
    {};
}

我知道它的应用,但这究竟是如何工作的?

1 个答案:

答案 0 :(得分:1)

如果没有指向原始代码的链接,则会遗漏很多内容。我猜你在问你在这里复制的片段。

此代码段有两个部分,两者都没有较大的上下文无关。第一个是int_sequencemake_int_sequence

首先,目的:make_int_sequence<3>继承自int_sequence<0, 1, 2>int_sequence只是一组索引的类型容器,make_int_sequence<N>是一个生成器类型,它生成从0到N-1的int_sequence索引。

如果您遵循该代码,则make_int_sequence<3>继承自make_int_sequence<2, 2>,该make_sequence<1, 1, 2>继承自make_sequence<0, 0, 1, 2>,继承自int_sequence<0, 1, 2>。{ / p>

(在C ++ 14中,存在std::integer_sequence和朋友来做这件事。)

第二部分是placeholder_template。由于std::placeholders::_1_2等属于不确定类型,我们创建自己的方式是创建一个类型,然后为该类型专门化std::is_placeholder。在这种情况下,该类型为placeholder_template。关于// the one is important的评论指的是placeholder_template<0>的行为与_1类似,两者都必须从std::integral_constant<int, 1>继承。

然后,链接中的实际代码使用make_integer_sequence构建一组基于0的索引,然后为每个索引生成一个占位符。