【发布时间】:2014-08-07 04:17:45
【问题描述】:
我有很多这样的字符串:
"343536"_hex
我想转换成它们对应的字节串。我正在使用 C++11 并定义了一个用户定义的字符串文字来将它们转换为十六进制字符串。但是,我目前的转换无法评估为constexpr,这正是我所寻求的。特别是我想使用这样的东西,但作为constexpr:
std::string operator "" _hex(const char *s, std::size_t slen )
{
std::string str;
str.reserve(slen);
char ch[3];
unsigned long num;
ch[2] = '\0';
for ( ; slen; slen -= 2, s += 2) {
ch[0] = s[0];
ch[1] = s[1];
num = strtoul(ch, NULL, 16);
str.push_back(num);
}
return str;
}
测试驱动
int main()
{
std::string src{"653467740035"_hex};
for (const auto &ch : src)
std::cout << std::hex << std::setw(2) << std::setfill('0')
<< (unsigned)ch << '\n';
}
样本输出
65
34
67
74
00
35
问题
要非常非常清楚我在问什么,是这样的:
如何编写这种类型的 C++11 字符串文字转换,可以在编译时评估为 constexpr?
【问题讨论】:
-
This doesn't quite work有点轻描淡写,constexpr函数中的大多数类型都不是文字类型,它们不能在编译时使用。 -
我已对问题进行了编辑以使其更加清晰。作为记录,是的,我知道这种转换不会像
constexpr那样工作——这是问题的本质。
标签: c++ string c++11 type-conversion