Initialisation of static vector

前端 未结 6 465
遥遥无期
遥遥无期 2020-12-13 23:48

I wonder if there is the \"nicer\" way of initialising a static vector than below?

class Foo
{
    static std::vector MyVector;
    Foo()
    {
           


        
6条回答
  •  余生分开走
    2020-12-14 00:06

    Typically, I have a class for constructing containers that I use (like this one from boost), such that you can do:

    const list primes = list_of(2)(3)(5)(7)(11);
    

    That way, you can make the static const as well, to avoid accidental modifications.

    For a static, you could define this in the .cc file:

    // Foo.h
    
    class Foo {
      static const vector something;
    }
    
    // Foo.cc
    
    const vector Foo::something = list_of(3)(5);
    

    In C++Ox, we'll have a language mechanism to do this, using initializer lists, so you could just do:

    const vector primes({2, 3, 5, 7, 11});
    

    See here.

提交回复
热议问题