Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

string - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...