C ++:宏可以扩展“abc”成'a','b','c'? [英] C++: Can a macro expand "abc" into 'a', 'b', 'c'?

查看:113
本文介绍了C ++:宏可以扩展“abc”成'a','b','c'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个可变参数模板来接受 char 参数的可变数,例如

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">

Foo<SOME_MACRO("abc")>

Foo<SOME_MACRO(abc)>

等。

基本上,

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.

推荐答案

我今天创建了一个,并在GCC4.6.0上测试。

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;
};

一些测试

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")());
}

所以当你没有得到一个 ','b','c',仍然会获得编译时字符串。

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

这篇关于C ++:宏可以扩展“abc”成'a','b','c'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆