User Defined Literals for a String versus for a Hex Value

Ste*_*eve 3 c++ user-defined-literals c++11

Regarding this question, why does a a user defined literal for a hex value map to a different string literal operator than a string does? That is, why does the code

std::vector<uint8_t> val1 = 0x229597354972973aabbe7_hexvec;
Run Code Online (Sandbox Code Playgroud)

map to

std::vector<uint8_t> operator"" _hexvec(const char*str)
{
    // Handles the form 0xFFaaBB_hexvec and 0Xf_hexvec
    size_t len = strlen(str);
    return convertHexToVec(str, len);   
}
Run Code Online (Sandbox Code Playgroud)

while the code

std::vector<uint8_t> val2 = "229597354972973aabbe7"_hexvec;
Run Code Online (Sandbox Code Playgroud)

maps to

std::vector<uint8_t> operator"" _hexvec(const char*str, std::size_t len)
{
    // Handles the conversion form "0xFFAABB"_hexvec or "12441AA"_hexvec
    return convertHexToVec(str, len);
}
Run Code Online (Sandbox Code Playgroud)

What makes the size_t necessary when both are null terminal strings? For that matter, why is 0x551A_hexvec a string at all? Why not an integer?

Nic*_*las 5

What makes the size_t necessary when both are null terminal strings?

There ain't no rule in C++ that a string literal cannot have NUL characters embedded in it. "Nul\0character" is a valid C++ string literal. And when doing UDL processing, the C++ language wants to make sure that you know which bytes are actually part of the string. To do that, you need a size.

Also, it allows the system to differentiate between literals intended to operate on strings and literals intended to operate on numbers. The literal 21s could mean 21 seconds, while the literal "21"s can mean a std::string containing the character string "21". And both literals can be in-scope without any kind of cross-talk.

Numeric literal UDL functions don't take a size_t to differentiate themselves from an overload intended for string literals. However, numeric literal cannot have a NUL-character in it, so they don't lose much by not being given a size.

For that matter, why is 0x551A_hexvec a string at all? Why not an integer?

Because that's what you asked for.

数字文字的 UDL 函数可以处理原始文字数据(作为字符串)或合成文字值。如果您使用const char*UDL的版本,则您要求处理原始文字数据。

合成文字值是使用文字的常规规则从文字计算出的 C++ 类型。对于整数数字文字,合成文字值是unsigned long long: C++ 可用的最大基本整数类型:

std::vector<uint8_t> operator"" _hexvec(unsigned long long value);
Run Code Online (Sandbox Code Playgroud)

当然,这其实unsigned long long是一个的有限的尺寸也正是原始文字版本存在。文字0x229597354972973aabbe7无法放入unsigned long long,但您可能仍然希望能够将其放入您生成的对象中。因此,您必须能够访问文字值的实际字符。