C++11 Fun with initializer lists, arrays, and enumerations

后端 未结 5 1753
天涯浪人
天涯浪人 2021-01-03 03:27

Background

C++11 initializer lists can be used to initialize vectors and arrays with argument passing to constructors.

I have a piece of code below

5条回答
  •  情歌与酒
    2021-01-03 03:58

    You can do this with variadic templates and what I'm going to call the "indices trick".

    typedef std::underlying_type::type underlying;
    
    // just a type to carry around variadic pack of numbers
    template  struct indices {};
    
    // A template to build up a pack of Count numbers from first
    // third parameter is an accumulator
    template >
    struct make_indices;
    
    // base case
    template 
    struct make_indices> { typedef indices type; };
    // recursive build up of the pack
    template 
    struct make_indices>
        : make_indices> {};
    
    size_t const max_colors = underlying(eCOLORS::Last) - underlying(eCOLORS::First)+1;
    
    // shortcut
    typedef make_indices<
              underlying(eCOLORS::First),
              max_colors
            >::type all_eCOLORS_indices;
    
    // takes a dummy parameter with the pack we built
    template 
    std::array const& all_colors(indices) {
        // convert each number to the enum and stick it in an static array
        static std::array const all = {
            eCOLORS(Indices)...
        };
        return all;
    }
    
    std::array const& all_colors() {
        // create a dummy object of the indices pack type and pass it
        return all_colors(all_eCOLORS_indices());
    }
    

    This assumes all the enumerators are sequential, and needs std::underlying_type which is not supported in GCC 4.6 (will be in 4.7, but you can emulate it to a certain extent).

提交回复
热议问题