作者:lydia芸小窝的天使 | 来源:互联网 | 2022-12-10 14:35
我的代码使用了一个使用模板化函数的库(FastLED):
#define NUM_WIDGETS 4
Library.function<1>();
Library.function<2>();
Library.function<3>();
Library.function<4>();
我不能把它放在一个正常的for循环中,因为模板参数需要在编译时可计算.我可以在预处理器中执行此操作吗?还有其他建议吗?我希望能够方便地更改NUM_WIDGETS,而无需复制粘贴这些行.
1> Miles Budnek..:
您可以在以下帮助下使用模板执行此操作std::index_sequence
:
constexpr size_t NUM_WIDGETS = 4;
template
void foo() {
std::cout <
void call_foo_helper(std::index_sequence) {
(foo(), ...);
}
template
void call_foo() {
call_foo_helper(std::make_index_sequence());
}
int main() {
call_foo();
}
这使用C++ 17倍表达式.如果您没有可用的C++ 17,则可以使用递归模板:
constexpr size_t NUM_WIDGETS = 4;
template
void foo() {
std::cout <
void call_foo() {
foo();
call_foo();
}
template <>
void call_foo<0>() { }
int main() {
call_foo();
}