以下是无法编译的示例代码。
我们使用迭代函数在一定范围内进行迭代并运行lambda回调函数。迭代函数会将一些指示(即类型)传递给回调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;
});
}
最佳答案
您不能将运行时变量用作模板参数,该参数应该是编译时常量。但是您可以将常量包装到 std::integral_constant
中,以将常量值编码为一种类型:
template<typename Func>
void iterate(Func func) {
for(int i = 0; i < 5; ++i)
func(std::integral_constant<int, 0>{}, i);
for(int i = 0; i < 5; ++i)
func(std::integral_constant<int, 1>{}, i);
}
template<int d>
int getValue(int i) {
return d + i;
}
int main() {
iterate([&](auto type, int index) {
std::cout << getValue<type>(index) << std::endl;
});
}
std::integral_constant
可以隐式转换为基础类型的值。在getValue<type>(index)
中,type
转换为int
类型的包装值。Demo
关于c++ - lambda函数使用其参数作为模板参数调用模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61796664/