如何将 std::dec/hex/oct 放入查找数组中
我有这个通用字符串到数字的转换:
enum STRING_BASE : signed int {
BINARY = -1,
OCTAL = 0,
DECIMAL = 1,
HEX = 2,
};
template <class Class>
static bool fromString(Class& t, const std::string& str, STRING_BASE base = DECIMAL) {
if (base == BINARY) {
t = (std::bitset<(sizeof(unsigned long)*8)>(str)).to_ulong();
return true;
}
std::istringstream iss(str);
std::ios_base& (*f)(std::ios_base&); /// have no idea how to turn this into a look-up array
switch (base) {
case OCTAL: f = std::oct; break;
case DECIMAL: f = std::dec; break;
case HEX: f = std::hex; break;
}
return !(iss >> f >> t).fail();
};
我想将 switch 情况转换为一个精细的查找数组,沿着这些思路:
std::ios_base arr[2] = {std::oct, std::dec, std::hex};
return !(iss >> arr[(int)base] >> t).fail();
这会产生:*错误 C2440:'初始化':无法转换从 'std::ios_base &(__cdecl )(std::ios_base &)' 到 'std::ios_base'
这也不起作用:
std::ios_base& arr[2] = {std::oct, std::dec, std::hex};
我得到:错误 C2234: 'arr' : 引用数组非法
那么,这个问题有什么解决办法吗?
I have this generic string to number conversion :
enum STRING_BASE : signed int {
BINARY = -1,
OCTAL = 0,
DECIMAL = 1,
HEX = 2,
};
template <class Class>
static bool fromString(Class& t, const std::string& str, STRING_BASE base = DECIMAL) {
if (base == BINARY) {
t = (std::bitset<(sizeof(unsigned long)*8)>(str)).to_ulong();
return true;
}
std::istringstream iss(str);
std::ios_base& (*f)(std::ios_base&); /// have no idea how to turn this into a look-up array
switch (base) {
case OCTAL: f = std::oct; break;
case DECIMAL: f = std::dec; break;
case HEX: f = std::hex; break;
}
return !(iss >> f >> t).fail();
};
I would like to turn the switch case into a fine look-up array, something along these lines:
std::ios_base arr[2] = {std::oct, std::dec, std::hex};
return !(iss >> arr[(int)base] >> t).fail();
This produces : *error C2440: 'initializing' : cannot convert from 'std::ios_base &(__cdecl )(std::ios_base &)' to 'std::ios_base'
This won't work either :
std::ios_base& arr[2] = {std::oct, std::dec, std::hex};
I get : error C2234: 'arr' : arrays of references are illegal
So, is there any solution to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试:
或者使用 typedef 作为函数指针:
您可以省略数组大小,它将由初始值设定项的数量确定。 我注意到这一点是因为您指定了一个大小为 2 的数组,但提供了 3 个初始值设定项。
Try:
Or with typedef for the function pointer:
You can omit the array size, it will be deteremined from the number of initializers. I noticed this because you specified an array of size 2, but provided 3 initializers.