将变量作为模板参数传递 [英] Passing a variable as a template argument
问题描述
我正在使用一个公开使用接口的库。该库的功能之一是这样的:
I am working with a library which exposes an interface to work with. One of the functions of this library is like this :
template <int a>
void modify(){}
我必须将参数从1修改为10,即调用 modify
的模板参数为1到10。为此,我编写了这段代码(基本版本的代码,实际代码要大得多)。
I have to modify parameters from 1 to 10 i.e. call modify
with with template arguments from 1 to 10. For that I wrote this code (a basic version of code, actual code is much larger).
for(int i=0; i<10; i++){
modify<i>();
}
在编译时收到以下错误
error: 'i' cannot appear in constant-expression
浏览了Internet上的某些链接后,我知道我不能将任何值作为模板参数传递,而该值在编译时未进行评估。
我的问题如下:
1.为什么编译器在编译时不能评估 i
?
2.在不更改API接口的情况下,还有其他目标可以实现吗?
After going through some links on the internet, I came to know that I cannot pass any value as template argument which is not evaluated at compile time.
My question are as follows:
1. Why can't compiler evaluate i
at compile time?
2. Is there any other to achieve the objective I am trying to achieve without changing the API interface?
还有另一件事我想做。调用Modify作为Modify,其中VAR是某些函数计算的输出。我怎样才能做到这一点?
There is another thing I want to do. Call modify as modify where VAR is the output of some functional computation. How can I do that?
推荐答案
在编译时 i 的值是什么(不是常数)?除非执行循环,否则无法回答。但是执行不是编译
既然没有答案,编译器就不能这样做。
What is the value of i (that is not a constant) at compile time? There is no way to answer unless executing the loop. But executing is not "compiling" Since there is no answer, the compiler cannot do that.
模板不是要执行的算法,而是要执行的宏扩展生成代码。
您可以做的是依靠专业化来实现递归迭代,例如:
Templates are not algorithm to be executed, but macros to be expanded to produce code. What you can do is rely on specialization to implement iteration by recursion, like here:
#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>()();
}
请注意,这样做实际上是实例化了10个函数名为
modify< 0>
... modify< 9>
,分别由<$ c $调用c> static_for< 0,10> :: operator() ... static_for< 9,10> :: operator()
。
Note that, by doing this, you are, in fact, instantiating 10 functions named
modify<0>
... modify<9>
, called respectively by static_for<0,10>::operator()
... static_for<9,10>::operator()
.
迭代将结束,因为 static_for< 10,10>
将从采用两个相同值的专业化实例化,没什么。
The iteration ends because static_for<10,10>
will be instantiated from the specialization that takes two identical values, that does nothing.
这篇关于将变量作为模板参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!