我想使用indices trick消除C++ 11程序中的for循环(类似于force -funroll-loops)。

这是一个例子:

template<unsigned...> struct indices
{
};

template<unsigned M, unsigned... Is> struct indices_gen
  : indices_gen<M - 1, M - 1, Is...>
{
};

template<unsigned... Is> struct indices_gen<0, Is...> : indices<Is...>
{
};

template <typename T>
struct example
{
  example()
  {
    assign(indices_gen<3>(), 0);
  }

  template<unsigned... Is, typename U>
  void assign(indices<Is...>, U value)
  {
    [](...){}((array[Is] = value)...);
  }

  T array[3];
};

int main()
{
  example<int> ex;
  return 0;
}

是否可以创建indices_gen<S,E>,从开始索引S到结束索引E?你能告诉我如何吗?

最佳答案

试试这个(http://liveworkspace.org/code/e65a81d0d3e9b17692713fd3e9d681f5):

template<unsigned...> struct indices {};

template<unsigned S, unsigned E, unsigned... Is> struct indices_gen
  : indices_gen<S, E-1, E-1, Is...>
{};

template<unsigned S, unsigned... Is> struct indices_gen<S, S, Is...> : indices<Is...>
{};

工作示例:http://liveworkspace.org/code/3d0ba21cc637a61c3e63d2db002f87af

编辑:检查Xeo的评论。上面的示例没有检查S < E,因此如果输入错误,它可能会变坏。在这种情况下,此(Xeo的代码)将返回编译器错误:http://liveworkspace.org/code/81205e13334e89537bdc0b79b3ba56fc

09-05 06:41