C++ macro to convert a string to list of characters

后端 未结 2 1464
我寻月下人不归
我寻月下人不归 2021-01-12 22:12

Is it possible to have a macro to have:

CHAR_LIST(chicken)

to expand to:

\'c\', \'h\', \'i\', \'c\', \'k\', \'e\', \'n\'

[Reason I want it: b

相关标签:
2条回答
  • Update by the answerer, July 2015: Due to the comments above on the question itself, we can see the the real question was not about macros per se. The real problem the questioner wanted to solve was to be able to pass a literal string to a template that accepts a series of chars as non-type template arguments. Here is an ideone demo of a solution to that problem. The implementation there requires C++14, but it's easy to convert it to C++11.

    ------------

    I think we need a clearer example of how this macro is to be used. We need an example of the variadic template. (Another Update: This won't work doesn't work for me on g++ 4.3.3 in a variadic template even when c++0x support is turned on, but I think it might be interesting anyway.)

    #include<iostream> // http://stackoverflow.com/questions/6190963/c-macro-to-convert-a-string-to-list-of-characters
    #include "stdio.h"
    
    using namespace std;
    
    #define TO_STRING(x) #x
    #define CHAR_LIST_7(x)   TO_STRING(x)[0] \
                           , TO_STRING(x)[1] \
                           , TO_STRING(x)[2] \
                           , TO_STRING(x)[3] \
                           , TO_STRING(x)[4] \
                           , TO_STRING(x)[5] \
                           , TO_STRING(x)[6] \
    
    int main() {
            cout << TO_STRING(chicken) << endl;
            printf("%c%c%c%c%c%c%c", CHAR_LIST_7(chicken));
    }
    

    The line defining d is what you're interested in. I've included other examples to show how it's built up. I'm curious about @GMan's link to automate the counting process.

    0 讨论(0)
  • 2021-01-12 22:38

    Nope, sorry, can't be done. There is no operation to split a string into characters. The closest you could get is through recursive metaprogramming, but that will give you the array as an object, not the actual text representation.

    0 讨论(0)
提交回复
热议问题