我正在使用一个库来公开一个可以使用的接口.这个库的一个功能是这样的:
template <int a>
void modify(){}
Run Code Online (Sandbox Code Playgroud)
我必须修改从1到10的参数,即modify使用模板参数从1到10 调用.为此,我编写了这段代码(代码的基本版本,实际代码要大得多).
for(int i=0; i<10; i++){
modify<i>();
}
Run Code Online (Sandbox Code Playgroud)
在编译时,我收到以下错误
error: 'i' cannot appear in constant-expression
Run Code Online (Sandbox Code Playgroud)
通过互联网上的一些链接后,我开始知道我不能传递任何值作为模板参数,这在编译时不会被评估.我的问题如下:1.为什么i编译时无法编译评估?2.还有其他任何方法可以实现我想要在不改变API接口的情况下实现的目标吗?
还有一件事我想做.调用修改为修改,其中VAR是某些功能计算的输出.我怎样才能做到这一点?
Emi*_*lia 33
编译时i的值(不是常数)是多少?除非执行循环,否则无法使用.但执行不是"编译"因为没有答案,编译器不能这样做.
模板不是要执行的算法,而是要扩展以生成代码的宏.你可以做的是依靠专门化来通过递归来实现迭代,就像这里:
#include <iostream>
template<int i>
void modify()
{ std::cout << "modify<"<<i<<">"<< std::endl; }
template<int x, int to>
struct static_for
{
void operator()()
{ modify<x>(); static_for<x+1,to>()(); }
};
template<int to>
struct static_for<to,to>
{
void operator()()
{}
};
int main()
{
static_for<0,10>()();
}
Run Code Online (Sandbox Code Playgroud)
请注意,通过执行此操作,您实际上是实例化名为modify <0> ... modify <9>的10个函数,分别由static_for <0,10> :: operator()... static_for <9调用, 10> ::运算符().
迭代结束是因为static_for <10,10>将从具有两个相同值的特化中实例化,而不执行任何操作.
| 归档时间: |
|
| 查看次数: |
20329 次 |
| 最近记录: |