【发布时间】:2020-05-14 11:51:23
【问题描述】:
以下是示例代码,无法编译。
我们使用 iteration 函数来迭代某个范围并运行 lambda 回调函数。 iterate 函数会将一些指示(即 type)传递给回调 lambda 函数,然后它会根据指示进行工作。由于这些指示在编译时是固定的,我相信有一种方法可以在运行时消除所有指示开销。但是如何..?
template<typename FuncT>
void iterate(const FuncT& func) {
for(int i = 0; i < 5; ++i)
func(0, i);
for(int i = 0; i < 5; ++i)
func(1, i);
}
template<int d> int getValue(int i) { return d+i; }
// this has run-time overhead compared to the template version
// int getValue(int d, int i) {return d+i; }
int main() {
iterate([&](const int type, int index){
// error: cannot compiler here
// candidate template ignored: invalid explicitly-specified argument for template parameter 'd'
std::cout<<getValue<type>(index)<<std::endl;
});
}
【问题讨论】:
-
在
getValue<type>(index)中,类型的值必须在编译时知道,但直到在运行时调用 lambda 时才知道。你到底想达到什么目标? -
@WernerHenze 你是对的。它只是一个示例代码。在我的项目中,传递给 lambda 函数的参数(即类型)在编译时是已知的。我只是想知道有没有办法通过模板将它从运行时中删除。我猜 Evg 提供了一个非常酷的解决方案。
标签: c++ templates metaprogramming