0

Is it possible to write a macro in C/C++ pre-processer that expands its single argument to the component characters it is composed of

For example

EXPAND( abcd )

would expand to

'a', 'b', 'c', 'd'

Other examples are

EXPAND( 1 )
'1'
EXPAND( 12 )
'1', '2'
EXPAND( func_name )
'f', 'u', 'n', 'c', '_', 'n', 'a', 'm', 'e'

EDIT:

The purpose would be to pass a character sequence as a parameter to a template like the one below

template<char...  args>
struct  Struct {
    ... 
};

Instead of having to code the tedious

Struct<'a', 'b', 'c'>

one would simply do

Struct<EXPAND( abc )>

Ideally it would be best if one could code

Struct<"abc">

but string literals are not converted into char... sequences automatically.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
D R
  • 21,936
  • 38
  • 112
  • 149
  • No. IMHO macros are best to avoid – Ed Heal Nov 09 '15 at 20:14
  • 2
    What purpose would such a macro serve? It would just make the code even harder to understand. – owacoder Nov 09 '15 at 20:17
  • I added an explanation of the purpose as an edit. – D R Nov 09 '15 at 20:29
  • You might want to share more of the idea of this template. Maybe the idea is fundamentally broken and another approach can eliminate the requirement you are asking for. – cadaniluk Nov 09 '15 at 20:47
  • 2
    Have a look at this: http://abel.web.elte.hu/mpllibs/metaparse/string.html I think it does exactly what you are asking for. Here is an overview: http://2012.cppnow.org/session/metaparse-complie-time-parsing-with-template-metaprogramming/ and http://web.archive.org/web/20140217173026/http://cpp-next.com/archive/2012/10/using-strings-in-c-template-metaprograms – Jerry Jeremiah Nov 09 '15 at 21:03

1 Answers1

3

No. This functionality is not provided by the C preprocessor.

Depending on your use case, a string might be equivalent (except for the null byte), so stringifying might work as well.

You might have a look at m4, a more advanced preprocessor by K&R. Maybe it provides the functionality you need.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67