【问题标题】:BOOST_PP_SEQ_ENUM with single quotes?BOOST_PP_SEQ_ENUM 带单引号?
【发布时间】:2019-02-16 17:11:32
【问题描述】:

基本上我想将单个标记拆分为用单引号括起来的多个标记,但由于这似乎不可能,我已经停止this。基本上:

#include <boost/preprocessor/seq/enum.hpp>

char string[] = {BOOST_PP_SEQ_ENUM((F)(l)(y)(O)(f)(f)(L)(e)(d)(g)(e))};

但是如何添加单引号呢?

【问题讨论】:

  • 可以在编译时将字符串文字拆分为单独的字符,而无需任何宏。
  • @VTT,小心,C++ 标签已被移除。

标签: c boost macros preprocessor boost-preprocessor


【解决方案1】:

我认为不可能在符合标准的 C 中创建字符文字,请参阅C preprocessor: How to create a character literal?

但是,如果你只想要字符,你有几个选择:

  • 您可以使用BOOST_PP_STRINGIZEBOOST_PP_SEQ_CAT 将其扩展为字符串文字:

    char string[] = BOOST_PP_STRINGIZE(
        BOOST_PP_SEQ_CAT((F)(l)(y)(O)(f)(f)(L)(e)(d)(g)(e)));
    // Equivalent to:
    char string2[] = "FlyOffLedge";
    

    Live on Godbolt

  • 您可以将每个字符扩展为"c"[0]

    #define TO_CSV_CHARS_OP(s, data, elem) BOOST_PP_STRINGIZE(elem)[0]
    #define TO_CSV_CHARS(seq) \
        BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(TO_CSV_CHARS_OP, , seq))
    
    char string[] = {
        TO_CSV_CHARS((F)(l)(y)(O)(f)(f)(L)(e)(d)(g)(e))
    };
    // Equivalent to:
    char string2[] = {
        "F"[0],
        "l"[0],
        "y"[0],
        "O"[0],
        "f"[0],
        "f"[0],
        "L"[0],
        "e"[0],
        "d"[0],
        "g"[0],
        "e"[0]
    };
    

    Live on Godbolt

【讨论】:

    【解决方案2】:

    您可以很容易地将链接问题中的this answer 改编为 C 以实现最初的目标 (live example):

    #include <boost/preprocessor/repetition/repeat.hpp>
    #include <boost/preprocessor/punctuation/comma_if.hpp>
    
    #define GET_CH(s, i) ((i) >= sizeof(s) ? '\0' : (s)[i])
    
    #define STRING_TO_CHARS_EXTRACT(z, n, data) \
            BOOST_PP_COMMA_IF(n) GET_CH(data, n)
    
    #define STRING_TO_CHARS(STRLEN, STR)  \
            BOOST_PP_REPEAT(STRLEN, STRING_TO_CHARS_EXTRACT, STR)
    
    char string[] = {STRING_TO_CHARS(12, "FlyOffLedge")};
    

    我认为在 C 中不可能自动处理长度。

    如果您所追求的只是所问的问题,您可以使用 Justin 的回答中的技巧来获取每个字符串化字符的第一个字符,而无需使用字符文字语法 (similar live example)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多