0

I found this placeholder generator code which allows you to generate a sequence of a ints based off of the generic type template.

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
    {};
}

I know the applications of it, but how exactly does this work?

Community
  • 1
  • 1
FatalSleep
  • 307
  • 1
  • 2
  • 15

1 Answers1

1

Without your link to the original code, there's a lot missing. I'm guessing that you are asking about the snippet you copied here though.

There are two parts to this snippet, both unrelated without the larger context. The first is int_sequence and make_int_sequence.

First, the purpose: make_int_sequence<3> inherits from int_sequence<0, 1, 2>. int_sequence is just a type container for a set of indices, and make_int_sequence<N> is a generator type that generates the int_sequence of indices from 0 to N-1.

If you follow the code, make_int_sequence<3> inherits from make_int_sequence<2, 2>, which inherits from make_sequence<1, 1, 2>, which inherits from make_sequence<0, 0, 1, 2>, which inherits from int_sequence<0, 1, 2>.

(In C++14, there exists std::integer_sequence and friends to do this.)

The second part is placeholder_template. Since std::placeholders::_1, _2, etc., are of indeterminate type, the way we can make our own is to create a type, and then specialize std::is_placeholder for that type. In this case that type is placeholder_template. The comment about // the one is important refers to the fact that placeholder_template<0> acts like _1, both of which must inherit from std::integral_constant<int, 1>.

The actual code from the link then uses make_integer_sequence to build a 0-based set of indices, and then generates a placeholder for each.

md5i
  • 3,018
  • 1
  • 18
  • 32