2009-08-08 33 views
0

我這個普通的字符串數轉換:如何把性病:: DEC /六角/月到查找陣列

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(); 
    }; 

我想打開開關情況下,成精的樣子-up陣列,沿着這些路線的東西:

std::ios_base arr[2] = {std::oct, std::dec, std::hex}; 
    return !(iss >> arr[(int)base] >> t).fail(); 

這產生:*錯誤C2440:初始化:不能從轉換 '的std ::的ios_base &(__cdecl )(標準::的ios_base &)' 到' std :: ios_base'

這也不行:

std::ios_base& arr[2] = {std::oct, std::dec, std::hex}; 

我得到:錯誤C2234: '常用3':引用數組是非法

那麼,有沒有辦法解決這個問題?

回答

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 }; 

可以省略數組的大小,它會從初始化符的數量來deteremined。我注意到了這一點,因爲你指定了一個大小爲2的數組,但提供了3個初始化器。