C++/C++11 Efficient way to have static array/vector of objects initialized with initializer list, and supporting range-based for

后端 未结 3 436
北恋
北恋 2020-12-15 07:29

Suppose you want to have a static array of pre-defined values/objects (const or non-const) associated with a class. Possible options are to use std:vector,

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 08:19

    I personally like your constexpr static int my_array[] = {MyClass{1, 2, 3}, MyClass{1, 2, 3}}; I don't think you should shy away from that if a C-style array meets your needs.

    If you really want to use std::vector though you could use static const std::vector vec_pre;. So your .cpp file would have this at the top:

    namespace{
        MyClass A{1, 2, 3}, B{1, 2, 3}, C{1, 2, 3};
    }
    const std::vector MyClass::vec_pre{&A, &B, &C};
    

    EDIT after DarkMatter's comments:

    After reading your comments, it looks like there could be some maintainability hazard to my method. It could still be accomplished like this in your .cpp:

    namespace{
        MyClass temp[]{MyClass{1, 2, 3}, MyClass{1, 2, 3}, MyClass{1, 2, 3}};
        const MyClass* pTemp[]{&temp[0], &temp[1], &temp[2]};
    }
    const std::vector MyClass::vec_pre{begin(pTemp), end{pTemp}};
    

    You could also remove the duplication of entry maintainability problem by creating a macro to do that for you.

提交回复
热议问题