【问题标题】:How to put std::dec/hex/oct into a look-up array如何将 std::dec/hex/oct 放入查找数组
【发布时间】:2009-08-08 10:17:18
【问题描述】:

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

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

我想把 switch 的情况变成一个很好的查找数组,大致如下:

    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':引用数组是非法的

那么,有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: c++ arrays lookup std


    【解决方案1】:

    试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 2015-11-08
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2020-09-12
      • 2015-06-21
      相关资源
      最近更新 更多