7
votes

Currently, only doubles can produce a template of chars in a user defined literal:

template <char...> double operator "" _x();
// Later
1.3_x; // OK
"1.3"_y; // C++14 does not allow a _y user-
         // defined operator to parse that as a template of chars

Is there a clever way to produce a std::integer_sequence of chars using a user defined literal. In other words, what the code of _y(const char*, std::size_t) would be so that I end up with a std::integer_sequence<char, '1', '.', '3'>?

1
N3599 may make it into C++1Z.Columbo
Do you really need an integer_sequence? This smells like an XY-problem.Columbo
@Columbo Where did you get that information? Last I heard it was rejected in EWG in favor of a string_literal<N>.T.C.
@T.C. Straight from the author.Columbo
If you don't want to use compiler extensions, the closest thing I know of is used like this: constexpr const char literal[] = "delta"; using X = make_char_sequence<sizeof(literal), literal>;. Let me know if you're interested in details.Rumburak

1 Answers

0
votes

At this point in time, the best we can (portably) do is a macro trick as demonstrated for vtmpl::string. Basically, we create a list of accesses such as

"abcd" -> {(0 < sizeof "abcd"? "abcd"[0] : 0), (1 < sizeof "abcd"? "abcd"[1] : 0), ...}

…which we trim to obtain the desired result.

The first step is easily done via BOOST_PP_ENUM, although recursive macros are also fine (definition from here):

#define VTMPL_SPLIT_1(s, x, m) m(s, x)
#define VTMPL_SPLIT_4(s, x, m)    VTMPL_SPLIT_1  (s, x, m), VTMPL_SPLIT_1  (s, x+1  , m), VTMPL_SPLIT_1  (s, x+2  , m), VTMPL_SPLIT_1  (s, x+3  , m)
#define VTMPL_SPLIT_16(s, x, m)   VTMPL_SPLIT_4  (s, x, m), VTMPL_SPLIT_4  (s, x+4  , m), VTMPL_SPLIT_4  (s, x+8  , m), VTMPL_SPLIT_4  (s, x+12 , m)
#define VTMPL_SPLIT_64(s, x, m)   VTMPL_SPLIT_16 (s, x, m), VTMPL_SPLIT_16 (s, x+16 , m), VTMPL_SPLIT_16 (s, x+32 , m), VTMPL_SPLIT_16 (s, x+48 , m)
#define VTMPL_SPLIT_256(s, x, m)  VTMPL_SPLIT_64 (s, x, m), VTMPL_SPLIT_64 (s, x+64 , m), VTMPL_SPLIT_64 (s, x+128, m), VTMPL_SPLIT_64 (s, x+194, m)
#define VTMPL_SPLIT_1024(s, x, m) VTMPL_SPLIT_256(s, x, m), VTMPL_SPLIT_256(s, x+256, m), VTMPL_SPLIT_256(s, x+512, m), VTMPL_SPLIT_256(s, x+768, m)

Usage of the above looks like this (trimming included):

#define VTMPL_STRING_IMPL(str, n) vtmpl::rtrim<vtmpl::value_list<decltype(*str), VTMPL_SPLIT_##n(str, 0, VTMPL_ARRAY_SPLIT)>>::type
#
#define VTMPL_STRING(str) VTMPL_STRING_IMPL(str, 64  )

Where rtrim is defined in algorithms.hxx.