title: C++11 Fun with initializer lists, arrays, and enumerations
body: <h3>Background</h3>
  
  <p>C++11 initializer lists can be used to initialize vectors and arrays with argument passing to constructors.</p>
  
  <p><strong>I have a piece of code below where I would like to initialize such an array with all the enumerations of <code>eCOLORS</code> from <code>eCOLORS::First</code> to <code>eCOLORS::Last</code> using initializer lists.</strong></p>
  
  <h3>Original Code</h3>
  
  <p>Since all information is known at compile time, I think there is a way to solve this problem.</p>
  
  <pre><code>enum class eCOLORS 
  {
      kBLUE=0, kGREEN, kRED, kPURPLE,
          First=kBLUE, Last=kPURPLE 
  };
  
  template&lt; typename E &gt;
  size_t Size()
  {
      return (size_t)(E::Last) - (size_t)(E::First) + 1;
  }
  
  struct Foo
  {
      Foo( eCOLORS color ) { }
  };
  
  int main(int argc, char** argv)
  {
      Foo a[2] = {
          { eCOLORS::kRED   },
          { eCOLORS::kGREEN }
      };  // works, but requires manual maintenance if I add another color
  
      /* how to feed v with all the enums from First to Last
         without hard-coding?
      Foo v[Size&lt;eCOLORS&gt;()] = {
  
      };
      */
  }
  </code></pre>
  
  <h3>Ugly Pseudo-Answer</h3>
  
  <p><em>The consensus appears to be that there is currently no way to this.</em></p>
  
  <blockquote>
    <p>My original intent in asking this question is, I want to automagically
    create an array of Foo objects whose initialization is solely based on
    the enumeration of <code>eColors</code>.  I wanted a no maintenance solution that
    would work even after you add more entries into <code>eColors</code>.</p>
  </blockquote>
  
  <p>Using the Enum class from <a href="https://stackoverflow.com/questions/8606315/c11-fun-with-initializer-lists-arrays-and-enumerations">this earlier post</a>, I can write a function template that gives me the functionality that I need.  Even without using that Enum class, you could still loop from <code>eCOLORS::First</code> to <code>eCOLORS::Last</code>, along with some ugly casts.</p>
  
  <p>My ugly pseudo-answer is kludgy (nowhere as nice as a compile-time initializer list), but at least it is zero maintenance.</p>
  
  <p>NOTE: if better solutions come up, I will update the OP accordingly.</p>
  
  <pre><code>template &lt;typename T, typename E&gt;
  std::vector&lt; T &gt;
  Initialize_With_Enums()
  {
    std::vector&lt; T &gt; v;
    for( auto p : Enum&lt;E&gt;() )
      v.push_back( T( p ));
    return v;
  }
  
  int main( int argc, char** argv )
  {
    auto w = Initialize_With_Enum&lt;Foo,eCOLORS&gt;();
  }
  </code></pre>