gpt4 book ai didi

C++ : using index as template parameter in for loop

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:18:21 25 4
gpt4 key购买 nike

给定以下模板和特化

enum CountryName 
{
Armenia = 0 ,
Georgia,
Size = 2
};

template <CountryName variable>
class CountryInfo;

template <>
class CountryInfo<Armenia>
{
/* CODE HERE */
};

template <>
class CountryInfo<Georgia>
{
/* CODE HERE */
};

我想遍历枚举并为每个特化创建对象。

main() {
for(auto i=0; i<CountryName::Size; ++i) {
CountryInfo<(static_cast<CountryName>(i))>();
}
}

我收到以下错误:错误:“i”的值在常量表达式中不可用 国家信息<(static_cast(i))>();

最佳答案

您想要的是将运行时变量转换为编译时变量(这是模板参数的要求)。有多种方法可以实现,例如

enum struct Country {
Armenia, Georgia, India
};

template<template<County> class Functor, typename... Args>
void LoopCountries(Args&&...args)
{
{ Functor<Armenia> func; func(std::forward<Args>(args)...); }
{ Functor<Georgia> func; func(std::forward<Args>(args)...); }
{ Functor<India> func; func(std::forward<Args>(args)...); }
}

假设Functor<>有成员(member)operator() .现在你可以简单地

LoopCountries<CountryInfo>();

一种更常见的情况是选择一个值(而不是遍历所有值):

template<template<County> class Functor, typename... Args>
void SwitchCountry(Country country, Args&&...args)
{
switch(country) {
case Armenia: { Functor<Armenia> func; func(std::forward<Args>(args)...); }
case Georgia: { Functor<Georgia> func; func(std::forward<Args>(args)...); }
case India: { Functor<India> func; func(std::forward<Args>(args)...); }
}
}

关于C++ : using index as template parameter in for loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51633594/

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