0

我有这个通用字符串到数字的转换:

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

这会产生: *error C2440: 'initializing' : cannot convert from 'std::ios_base &(__cdecl )(std::ios_base &)' to 'std::ios_base'

这也不起作用:

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

我得到:错误 C2234:'arr':引用数组是非法的

那么,有没有办法解决这个问题呢?

4

1 回答 1

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 个初始化程序。

于 2009-08-08T10:28:19.400 回答