在编译时将常量字符* 转换为常量 char_type*

Convert const char* to const char_type* at compile time

本文关键字:常量 char type 转换 字符 编译      更新时间:2023-10-16

请考虑以下代码:

using char_type = /*implementation defined*/;
void foo(const char_type*);
int main()
{
foo("Hello World!");
}

字符串文字"Hello World!"是一个const char*,根据实现的不同,可能无法转换为const char_type*。我希望我的代码可以在不同的实现之间移植,所以我想我可以定义一个文字来转换一个又一个字符(这种类型的转换保证有效(:

consteval const char_type* operator"" _s(const char*, size_t);

然后像这样使用它foo("Hello World!"_s).但是,我能想到的唯一实现使用new来分配空间和std::copy但这将非常慢。我想在编译时进行转换,幸运的是我可以使用 c++20 和consteval关键字来确保对函数的调用始终生成 contant 表达式(用户定义的文字仍然是普通函数,它们可以在运行时调用(。知道如何实现这一点吗?

此转换可以通过两步过程实现:首先,通过声明一个类,该类可以在编译时构造函数中将const char *转换为char_type数组;其次,通过在用户定义的文本中使用该类:

#include <algorithm>
template<std::size_t N>
struct string_convert {
char_type str[N] = {};
consteval string_convert(const char (&s)[N]) {
std::copy(s, s + N, str);
}
};
template<string_convert SC>
consteval auto operator ""_s()
{
return SC.str;
}

此接口允许以下用途:

void foo(const char_type *s);
foo("Hello, world!"_s);

在Godbolt上试试吧。请注意,string_convert和用户定义的文本都不会出现在反汇编中;剩下的就是转换后的数组。