以下是示例代码,无法编译。
We use 迭代函数来迭代某个范围并运行 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;
});
}
您不能使用运行时变量作为模板参数,它应该是编译时常量。但你可以将常量包装成std::integral_constant https://en.cppreference.com/w/cpp/types/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
转换为 type 的包装值int
.
Demo https://godbolt.org/z/QJmp8m
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)