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

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

问题描述

是否可以有一个宏:

CHAR_LIST(鸡肉)

CHAR_LIST(chicken)

展开为:

'c'、'h'、'i'、'c'、'k'、'e'、'n'

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

[我想要它的原因:因为即使是中等大小的字符串,宏也比手动扩展方便得多.我需要扩展的原因是将字符串传递给可变参数模板]

[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 支持,这个 won't work 对我在可变参数模板中的 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天全站免登陆