宏字符串连接
Macro string concatenation
我使用宏连接字符串,例如:
#define STR1 "first"
#define STR2 "second"
#define STRCAT(A, B) A B
有STRCAT(STR1 , STR2 )
产生"firstsecond"
。
在其他地方,我用这种方式将字符串与枚举相关联:
enum class MyEnum
{
Value1,
Value2
}
const char* MyEnumString[] =
{
"Value1String",
"Value2String"
}
STRCAT(STR1, MyEnumString[(int)MyEnum::Value1])
我只是想知道是否有可能建立一个宏,连接#define
d字符串字面值与const char*
?否则,我想我会做没有宏,例如以这种方式(但也许你有一个更好的方法):
std::string s = std::string(STR1) + MyEnumString[(int)MyEnum::Value1];
宏只适用于字符串字面值,即用双引号括起来的字符序列。宏工作的原因是c++标准将相邻的字符串字面值视为单个字符串字面值。换句话说,如果你写
,对编译器来说没有区别"Quick" "Brown" "Fox"
或
"QuickBrownFox"
在编译时,在程序开始运行之前执行连接。
const char*
变量的连接需要在运行时发生,因为字符指针(或任何其他指针)直到运行时才存在。这就是为什么你不能用你的CONCAT
宏做到这一点。不过,您可以使用std::string
进行连接,这是解决此问题最简单的方法之一。
这只适用于char
字量,它们可以以这种方式连接:
"A" "B"
对于示例中的指针表达式将不起作用,它将展开为像
这样的语句 "STR1" MyEnumString[(int)MyEnum::Value1];
至于你的编辑:
是的,我绝对会接受你的提议。
std::string s = std::string(STR1) + MyEnumString[(int)MyEnum::Value1];
宏是非常不必要的,因为它只能处理相同类型的字符串字面值。从功能上讲,它什么也不做。
std::string s = STRCAT("a", "b");
与
完全相同std::string s = "a" "b";
所以我觉得最好不要使用宏。如果你想要一个运行时字符串连接函数,一个更符合c++规范的版本是:
inline std::string string_concat(const std::string& a, const std::string& b)
{
return a + b;
}
但是,当您可以执行
时,使用这个函数似乎几乎没有意义std::string a = "a string";
std::string ab = a + "b string";
我可以看到像string_concat
这样的函数使用有限。也许你想工作在任意字符串类型或UTF-8和UTF-16之间的自动转换…
相关文章:
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 这两个C++语句连接字符串有什么区别?
- 连接字符串族
- 如何使用 + 运算符连接字符串
- 如何按照 Google C++风格指南连接字符串文字?
- 我的字符串类的 += 运算符有问题,它没有正确连接字符串
- 如何编写模板函数来添加整数但连接字符串和字符类型?
- 无法创建栅格堆栈,因为我无法连接字符串(dir_name + 文件名)
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 在std :: string中连接字符串的选项
- 连接字符串的最佳方法是什么?
- 在实体框架C /CLI上配置连接字符串
- 在 c++ 中连接字符串和 int
- 如何连接字符串并传递给 system() 调用
- 有没有办法方便地为 Winsock send() 生成 HTTP 标头,而不是手动连接字符串
- 在可变参数模板函数中连接字符串(和数字)
- 连接字符串时出现意外问题
- 如何在 c++ 中连接字符串
- 自动连接字符串和 int C++
- 我的c++程序在我不告诉他的地方连接字符串