是否可以创建一个用户定义的文本,将字符串文本转换为 own 类型的数组?

Is it possible to create a user defined literal, which converts string literals to an array of own-type?

本文关键字:文本 字符串 转换 数组 类型 own 定义 创建 用户 一个 是否      更新时间:2023-10-16

是否可以创建一个用户定义的文字,将字符串文字转换为自己类型的数组?

假设我有自己的字节类型,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};
}

这符合你写的所有标准;你没有要求零泄漏。