C ++宏将字符串转换为字符列表 [英] C++ macro to convert a string to list of characters

查看:144
本文介绍了C ++宏将字符串转换为字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以拥有一个宏:

CHAR_LIST(鸡)

CHAR_LIST(chicken)

'c','h','i','c','k','e','n'

'c', 'h', 'i', 'c', 'k', 'e', 'n'

[原因我想要它:因为即使中等大小的字符串,宏是手动扩展非常方便。我需要扩展的原因是将一个字符串传递给一个varidiac模板]

[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]

推荐答案

2015年7月:由于上述问题本身的意见,我们可以看到真正的问题不是关于宏本身。提问者想要解决的真正的问题是能够将一个字符串传递给一个接受一系列字符作为非类型模板参数的模板。以下是该问题解决方案的 ideone 演示。这里的实现需要C ++ 14,但很容易将其转换为C ++ 11。

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.

我想我们需要一个更清楚的例子来说明如何使用这个宏。我们需要一个可变参数模板的例子。 (另一个更新:即使c ++ 0x支持已打开,这个不会工作在g ++ 4.3.3上不适用于可变参数模板,我认为这可能很有趣。)

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

定义 d 是你感兴趣的。我已经包括其他例子来展示它是如何建立的。我很好奇@GMAN的自动计数过程的链接。

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.

这篇关于C ++宏将字符串转换为字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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