是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?
Is it possible to create a user defined literal, which converts string literals to an array of own-type?
是否可以创建一个用户定义的文字,将字符串文字转换为自己类型的数组?
假设我有自己的字节类型,mylib::byte
:
namespace mylib {
enum class byte: unsigned char { };
}
因此,例如,"Hello"_X
应该具有mylib::byte[5]
的类型,值为{ 'H', 'e', 'l', 'l', 'o' }
。
这是背景,所以也许你可以推荐一些其他的解决方案。
我有一个 utf-8 类,它存储一个mylib::byte *
和一个长度(这就像std::string_view
一样,它不拥有内存区域(:
namespace mylib {
class utf8 {
const byte *m_string;
int m_length;
};
}
我希望能够方便地在代码中使用字符串文字构造mylib::utf8
,如下所示:
mylib::utf8 u = "Hello";
目前,我使用reinterpret_cast
,即 UB:
namespace mylib {
class utf8 {
const byte *m_string;
int m_length;
public:
utf8(const byte *s) {
m_string = s;
m_length = ...;
}
utf8(const char *s) {
m_string = reinterpret_cast<const byte *>(s); // causes UB afterwards
m_length = ...;
}
};
}
所以我想,我想有这样的东西,以避免UB:
mylib::utf8 u = "Hello"_X; // I'd like to have the constructor with `const byte *` to be called here
注意:使用mylib::byte
是强制性的,我无法更改它。
mylib::utf8 operator "" _X(const char* c, std::size_t n) {
auto* r = new mylib::byte[n];
std::transform(c, c+n, r, [](auto c){ return (mylib::byte)(unsigned char)(c););
return {r,n};
}
这符合你写的所有标准;你没有要求零泄漏。
相关文章:
- 在 C++ 中从 8 位 ASCII 字符创建 7 位 ASCII 文本字符串
- cin>>gender 和 cin>>*gender ( c 样式文本字符串)有什么区别
- 是否可以动态检查文本字符串是否是 C++ 中给定类的成员?
- 用Zlib解压缩文本字符串
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 来自文本字符串或某种其他机制的代码类自动生成器
- 函数读取最大和min int值,并用文本字符串返回
- 模板代码和文本字符串
- 声明具有常量引用与常量变量的常量文本字符串
- 加密给定的文本字符串-Caesar Cipher
- 如何使用键盘输入和sf ::文本在SFML中添加一种文本框以显示文本字符串
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 如何将文本从一个文件复制到另一个文件,然后将文本字符串的第一个字母转换为大写
- 从文本字符串推断类型
- 跟踪内存中的文本字符串
- 将字符串变量与整数和文本字符串连接起来的 C++ 字符串流
- 将 char 数组分配给文本字符串 - C++
- 如何修复将文本字符串附加到 C 字符串的错误
- 使用C++读取不同长度的多个文本字符串
- 在C++中创建原始文本字符串,类似于 C# 的"@ string"