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++ 宏
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
