在编译时将常量字符* 转换为常量 char_type*
Convert const char* to const char_type* at compile time
请考虑以下代码:
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
和用户定义的文本都不会出现在反汇编中;剩下的就是转换后的数组。
相关文章:
- 是默认情况下分配给char数组常量的值
- 将错误作为从字符串常量到"char*"的已弃用转换 [-Wwrite-strings]
- 在<uint8_t> <char> c++ 中将常量向量转换为常量向量
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 将字符串文本常量定义为 char const* 和 wchar const*
- T = char* 的"常量 T"不是"常量字符*"?
- 将上一行添加到 char* 数组中的 char* 常量
- 如何在忽略 null 的同时将数据从 char [] 复制到常量字符 *
- 警告:ISO C++禁止将字符串常量转换为'char*' [-Wwrite-strings]
- 为什么在波纹管程序中发生了从字符串常量到'char*'的警告已弃用的转换
- 静态常量 std::<char>没有堆的向量初始化?
- 悬空指向 int 和 char* 常量的指针/引用
- 来自类型为std::basic_string::const_iterator的非常量引用的无效初始化,并且<char>来自类型std::basic_string<char>::
- 从 sub_match<常量字符 *>' 转换为'const char *const &'
- 某些常量char*在编译时不可用
- 常量 char* 的字符串构造函数更改常量 char* 的值
- 将两个常量char*组合在一起
- 可以将非常量char数组传递给函数作为常量char数组
- C++正在将常量char*转换为char*
- 为什么在每个函数的开头使用常量char指针?