Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Can a macro expand "abc" into 'a', 'b', 'c'?

I've written a variadic template that accepts a variable number of char parameters, i.e.

template <char... Chars> struct Foo; 

I was just wondering if there were any macro tricks that would allow me to instantiate this with syntax similar to the following:

Foo<"abc"> 

or

Foo<SOME_MACRO("abc")> 

or

Foo<SOME_MACRO(abc)> 

etc.

Basically, anything that stops you from having to write the characters individually, like so

Foo<'a', 'b', 'c'> 

This isn't a big issue for me as it's just for a toy program, but I thought I'd ask anyway.

like image 546
Peter Alexander Avatar asked Jan 03 '11 08:01

Peter Alexander


1 Answers

I've created one today, and tested on GCC4.6.0.

#include <iostream>  #define E(L,I) \   (I < sizeof(L)) ? L[I] : 0  #define STR(X, L)                                                       \   typename Expand<X,                                                    \                   cstring<E(L,0),E(L,1),E(L,2),E(L,3),E(L,4), E(L,5),   \                           E(L,6),E(L,7),E(L,8),E(L,9),E(L,10), E(L,11), \                           E(L,12),E(L,13),E(L,14),E(L,15),E(L,16), E(L,17)> \                   cstring<>, sizeof L-1>::type  #define CSTR(L) STR(cstring, L)  template<char ...C> struct cstring { };  template<template<char...> class P, typename S, typename R, int N> struct Expand;  template<template<char...> class P, char S1, char ...S, char ...R, int N> struct Expand<P, cstring<S1, S...>, cstring<R...>, N> :   Expand<P, cstring<S...>, cstring<R..., S1>, N-1>{ };  template<template<char...> class P, char S1, char ...S, char ...R> struct Expand<P, cstring<S1, S...>, cstring<R...>, 0> {   typedef P<R...> type; }; 

Some test

template<char ...S>  struct Test {   static void print() {     char x[] = { S... };     std::cout << sizeof...(S) << std::endl;     std::cout << x << std::endl;   } };  template<char ...C> void process(cstring<C...>) {   /* process C, possibly at compile time */ }  int main() {   typedef STR(Test, "Hello folks") type;   type::print();    process(CSTR("Hi guys")()); } 

So while you don't get a 'a', 'b', 'c', you still get compile time strings.

like image 130
Johannes Schaub - litb Avatar answered Oct 04 '22 10:10

Johannes Schaub - litb