提问人:Zachary Peterson 提问时间:11/5/2022 最后编辑:Zachary Peterson 更新时间:11/5/2022 访问量:58
使用可变参数模板初始化静态数组
Initialize static array with variadic template
问:
我有一个包含 Ingredient 类型的静态数组的结构配方,我想用可变参数模板构造它,以用任意数量填充数组。我查看了这里发布的其他问题,主要是:使用可变参数模板创建静态数组,但是当数组填充了{args...}时,数据不是输入的内容。这是在 msvc 中。
struct Ingredient
{
constexpr Ingredient(U16 id, U16 amount = 1, bool consumed = true) : id{ id }, amount{ amount }, consumed{ consumed } {}
U16 id;
U16 amount;
bool consumed;
};
struct Recipe
{
template<typename... Args>
constexpr Recipe(U16 result, U16 amount, U8 benchLevel, const Args&... args) :
result{ result }, amount{ amount }, benchLevel{ benchLevel }, ingredientCount{ sizeof...(args) }, ingredients{ {args...} }
{
}
U16 result;
U16 amount;
U8 benchLevel;
U16 ingredientCount;
Ingredient ingredients[];
};
class Items
{
public:
static const Item* GetItem(U16 id) { return items[id]; }
static const Recipe** GetRecipes() { return recipes; }
private:
static const Item* items[];
static const Recipe* recipes[];
Items() = delete;
};
inline const Recipe* Items::recipes[]
{
new Recipe(21, 1, 0, Ingredient{11}, Ingredient{12}),
new Recipe(22, 1, 0, Ingredient{11}, Ingredient{12}),
nullptr
};
使用代码:
void FillCraftingMenu()
{
const Recipe** recipes = Items::GetRecipes();
const Recipe* recipe = recipes[0];
U16 i = 0;
while (recipe)
{
bool found = true;
for (U16 j = 0; j < recipe->ingredientCount; ++j)
{
found &= inventory->ContainsItem(recipe->ingredients[j].id, recipe->ingredients[j].amount);
}
if (found)
{
//TODO: put up recipe
Logger::Debug("Recipe found: {}", recipe->result);
}
recipe = recipes[++i];
}
}
食谱中的成分表变为 [0] {id=65021,金额=65021,消耗量=false} [1] {id=0, amount=0, consumed=false}
答:
0赞
Zachary Peterson
11/5/2022
#1
因此,我发现的解决方案对我来说很有效:
template<typename... Args>
constexpr Recipe(U16 result, U16 amount, U8 benchLevel, const Args&... args) :
result{ result }, amount{ amount }, benchLevel{ benchLevel }, ingredientCount{ sizeof...(args) }, ingredients{ (Ingredient*)malloc(sizeof(Ingredient) * ingredientCount) }
{
U16 i = 0;
(void(ingredients[i++] = args), ...);
}
评论
malloc
operator new
std::vector<Ingredient>