用户定义字符串作为参数的整数字符序列 [英] Integer sequence of chars from user-defined literal taking strings as parameters
问题描述
目前,只有双精度型可以在用户定义的字面上产生一个字符模板:
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
有一个聪明的方法使用用户定义的字面量生成 std :: integer_sequence
的字符。换句话说, _y(const char *,std :: size_t)
的代码将是这样的,我最终得到一个 std :: integer_sequence< char,'1','。','3'>
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'>
?
推荐答案
在这个时间点,我们可以(可移植地)做的最好的是一个宏观的技巧,演示 vtmpl :: string
。基本上,我们创建一个访问列表,例如
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.
第一步很容易通过 BOOST_PP_ENUM
,但递归宏也很好(定义此处):
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 )
rtrim
定义在 algorithms.hxx
。
Where rtrim
is defined in algorithms.hxx
.
这篇关于用户定义字符串作为参数的整数字符序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!