views:

389

answers:

1

Hello. 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?

+2  A: 

Try:

std::ios_base& (*arr[])( std::ios_base& ) = { std::oct, std::dec, std::hex };

Or with typedef for the function pointer:

typedef std::ios_base& (*ios_base_setter)( std::ios_base& );

ios_base_setter arr[] = { std::oct, std::dec, std::hex };

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.

Charles Bailey