我想在我的C ++ 11程序中使用indices trick消除for
循环(类似于强制-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
?你能告诉我怎么样?
答案 0 :(得分:3)
试试这个(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