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

标签 c++ templates template-specialization

给定以下模板和特化

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/

相关文章:

c++ - 模板类中重载函数的条件编译

c++ - Clang 拒绝仅通过专门化定义类模板的嵌套类的代码是否正确?

template-specialization - 为什么概念类模板特化会导致错误

c++ - 如何从两个数组中生成一对 vector ,然后使用 CUDA/Thrust 按该对的第一个元素排序?

C++ 设置结构体数组中的元素 = NULL

C++ 库/框架,用于机器学习中混合模型的 API

c++ - C++ 编译器如何扩展模板 <> 代码以及它如何影响相同的速度?

c++ - 模板和 std::pair 列表初始化

c++ - 为什么不专门化函数模板呢? (问答)

c++ - 通过 STL 或 Boost 引入虚拟参数