宏字符串连接

Macro string concatenation

本文关键字:连接 字符串      更新时间:2023-10-16

我使用宏连接字符串,例如:

#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之间的自动转换…