【问题标题】:C++ initialize const static vector dynamicallyC++动态初始化const静态向量
【发布时间】:2012-12-15 20:13:01
【问题描述】:

我想在Foo 类中将static const std::vector 初始化为{0, 1, 2, 3, ..., n},其中n 在编译时基于下面enumLast 的值是已知的。目标是让Foo::all 包含Fruit 枚举的所有值。

foo.h:

enum Fruit { Apple, Orange, Banana, ..., Last };

class Foo {
public:
    static const vector<int> all;
};

foo.cpp:

// initialization of Foo::all goes here.

【问题讨论】:

    标签: c++ vector static initialization constants


    【解决方案1】:

    作为第三种选择:

    namespace {
      std::vector<int> create();
    }
    const std::vector<int> Foo::all = create();
    

    而且create() 可以做任何它喜欢的事情,甚至对每个元素都使用push_back(),因为它创建的vector 不是const。

    或者您可以使用&lt;index_tuple.h&gt;create() 设为constexpr 函数

    #include <redi/index_tuple.h>
    
    namespace {
      template<unsigned... I>
        constexpr std::initializer_list<int>
        create(redi::index_tuple<I...>)
        {
          return { I... };
        }
    }
    
    const std::vector<int> Foo::all = create(typename redi::make_index_tuple<Last>::type());
    

    【讨论】:

      【解决方案2】:

      你可以使用boost::irange:

      auto range = boost::irange(0, n + 1);
      const vector<int> Foo::numbers(range.begin(), range.end());
      

      【讨论】:

        【解决方案3】:

        如果您的n 足够小,并且您使用支持c++0xc++11 的编译器,只需将其拼写出来

        const std::vector<int> Foo::all{0, 1, 2, 3, ..., n};
        

        根据@Jonathan 的解释修复。

        【讨论】:

        • 惯用的 C++11 方式不会使用 = 符号。
        • @JonathanWakely,除了与BigInt i = 5;BigInt i(5); 相同的交易之外,还有什么区别,我从未真正看到过强烈的意见吗?
        • @JonathanWakely 好吧,我不知道。 g++ 接受任何一个。
        • 带有= 符号的它等同于vector&lt;int&gt; v = vector&lt;int&gt;{0, 1, 2, 3, ..., n}。 @chris 不同之处在于需要一个非显式构造函数和一个可访问的复制构造函数(显然vector 有,但并非所有类型都这样做。)例如std::unique_ptr&lt;int&gt; p = new int; 无效,但std::unique_ptr&lt;int&gt; p(new int); 有效。跨度>
        • @JonathanWakely 感谢您的解释,已修复。
        猜你喜欢
        • 1970-01-01
        • 2015-01-21
        • 2011-04-11
        • 2012-02-02
        • 2013-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-15
        相关资源
        最近更新 更多