C++ macro to convert a string to list of characters(将字符串转换为字符列表的 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++ 宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字符串转换为字符列表的 C++ 宏
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01