我将此通用字符串转换为数字转换:
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&amp;(__ cdecl )(std :: ios_base&amp;)'转换为'std :: ios_base'
这也不起作用:
std::ios_base& arr[2] = {std::oct, std::dec, std::hex};
我得到:错误C2234:'arr':引用数组是非法的
那么,这个问题是否有解决方案?
答案 0 :(得分:2)
尝试:
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个初始化器。