Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

macros

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: because for even moderate-sized strings, a macro is hugely more convenient than manually expanding. And the reason I need to expand is passing in a string to a varidiac template]

like image 207
Heptic Avatar asked May 31 '11 17:05

Heptic


2 Answers

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.

like image 135
Aaron McDaid Avatar answered Sep 24 '22 14:09

Aaron McDaid


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.

like image 34
Blindy Avatar answered Sep 23 '22 14:09

Blindy