给定以下模板和特化
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/