C++:在for循环中使用index作为模板参数

lib*_*.so 5 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 */
};
Run Code Online (Sandbox Code Playgroud)

我想迭代枚举并为每个专业化创建对象.

main() {
    for(auto i=0; i<CountryName::Size; ++i) {
        CountryInfo<(static_cast<CountryName>(i))>();
    }       
}   
Run Code Online (Sandbox Code Playgroud)

我得到以下错误: 错误:'i'的值在常量表达式CountryInfo <(static_cast(i))>();

Mik*_*yke 2

正如我在评论中所说,模板是在编译时解析的。即只有常量值可以用作模板参数,而变量则i不能。

您可以做的是某种递归模板迭代:

template<CountryName c>
struct ForLoop {
    template<template <CountryName> class Func>
    static void iterate() {
        ForLoop<static_cast<CountryName>(c - 1)>::template iterate<Func>();
        Func<c>()();
    }
};

//so that compiler knows when to stop
template <>
struct ForLoop<Armenia> {
  template <template <CountryName> class Func>
  static void iterate() {
    Func<Armenia>()();
  }
};

// CountryInfo needs an overloaded ()-operator, whcih get's called in the ForLoop
template <CountryName n>
struct CountryInfo {
  void operator()() { std::cout << n << std::endl; }
};

int main() {
  ForLoop<Georgia>::iterate<CountryInfo>();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

在 - 函数中调用main静态函数 get ,然后该函数从 Georgia 中减去 1 并再次调用该函数,直到它到达最后一个调用 get 的函数。如果您有任何疑问,请告诉我。ForLoop<Georgia>::iterateiterateForLoop<Armenia>::iterate