如何仅使用宏生成整数序列?

How to generate integer sequence with macro only?

我们知道,c++有std::make_integer_sequence,可以用来生成整数序列:std::make_index_sequence<size_t, N> => (0, ..., N-1).

我希望有一个宏MAKE_INTEGER_SEQUENCE(N)并且MAKE_INTEGER_SEQUENCE(3)会return(0)(1)(2)

如何只用宏实现呢? boost.preprocesser 解决方案也欢迎!

我试过 BOOST_PP_SEQ_FOR_EACH_I(macro, data, seq)macro(r, data, i, elem) (i)

This macro is a repetition construct. If seq is (a)(b)(c), it expands to the sequence: macro(r, data, 0, a) macro(r, data, 1, b) macro(r, data, 2, c)

但我必须提供一个 N 元素序列(如上面的 (a)(b)(c)),这对于此功能来说是多余的。

之所以希望它是一个宏,是因为我需要这样的sequences来生成多行代码,比如:

        ...... //primiary template above, specialize below, codes are from libcxx: https://github.com/llvm-mirror/libcxx/blob/master/include/__tuple#L130
        template<>
        struct parity<0>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type>
            {};
        };
        template<>
        struct parity<1>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type, Tp - 1>
            {};
        };
        template<>
        struct parity<2>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type, Tp - 2, Tp - 1>
            {};
        };
        template<>
        struct parity<3>
        {
            template<size_t Tp>
            struct pmake
                : repeat<typename make<Tp / 8>::type, Tp - 3, Tp - 2, Tp - 1>
            {};
        };
....

所以,宏是这里唯一的选择

您可以使用 BOOST_PP_REPEAT (live example):

轻松完成此操作
#include <boost/preprocessor.hpp>

#define TO_SEQ_ELEM(z, n, data) (n)
#define MAKE_INTEGER_SEQUENCE(n) BOOST_PP_REPEAT(n, TO_SEQ_ELEM, )

MAKE_INTEGER_SEQUENCE(10) // (0) (1) (2) (3) (4) (5) (6) (7) (8) (9)

请注意有一个重复限制,BOOST_PP_LIMIT_REPEAT,我测试时是 256,所以这是 n 的最大可能值。