我有这个通用字符串到数字的转换:
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();
};
我想将开关盒变成精细的查找数组,类似于以下内容:
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':引用数组是非法的
那么,有什么解决办法吗?
最佳答案
尝试:
std::ios_base& (*arr[])( std::ios_base& ) = { std::oct, std::dec, std::hex };
或使用typedef作为函数指针:
typedef std::ios_base& (*ios_base_setter)( std::ios_base& );
ios_base_setter arr[] = { std::oct, std::dec, std::hex };
您可以省略数组大小,它将根据初始化程序的数量确定。我注意到了这一点,因为您指定了一个大小为2的数组,但是提供了3个初始化器。
关于c++ - 如何将std::dec/hex/oct放入查找数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1248506/