是否可以创建用户定义的文字,将字符串文字转换为自己类型的数组?
假设我有一个自己的字节类型,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++ - 是否可以创建一个用户定义的文字,将字符串文字转换为自己类型的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245192/