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

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': 参照の配列が不正です

それで、この問題の解決策はありますか?

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 に答える