gpt4 book ai didi

C++动态初始化常量静态 vector

转载 作者:太空狗 更新时间:2023-10-29 19:46:19 25 4
gpt4 key购买 nike

我想将 Foo 类中的 static const std::vector 初始化为 {0, 1, 2, 3, ..., n 其中 n 在编译时根据下面 enum 中的 Last 的值已知。 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.

最佳答案

作为第三种选择:

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

create()可以为所欲为,甚至可以使用 push_back()对于每个元素,因为 vector它创建的不是 const。

或者你可以制作create()一个constexpr功能使用 <index_tuple.h>

#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());

关于C++动态初始化常量静态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14105485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com