这个for循环可以用预处理器完成吗?

Ann*_*nna 1 c++ templates arduino c-preprocessor fastled

我的代码使用了一个使用模板化函数的库(FastLED):

#define NUM_WIDGETS 4

Library.function<1>();
Library.function<2>();
Library.function<3>();
Library.function<4>();
Run Code Online (Sandbox Code Playgroud)

我不能把它放在一个正常的for循环中,因为模板参数需要在编译时可计算.我可以在预处理器中执行此操作吗?还有其他建议吗?我希望能够方便地更改NUM_WIDGETS,而无需复制粘贴这些行.

Mil*_*nek 5

您可以在以下帮助下使用模板执行此操作std::index_sequence:

constexpr size_t NUM_WIDGETS = 4;

template <size_t N>
void foo() {
    std::cout << N << '\n';
}

template <size_t... Ns>
void call_foo_helper(std::index_sequence<Ns...>) {
    (foo<Ns>(), ...);
}

template <size_t N>
void call_foo() {
    call_foo_helper(std::make_index_sequence<N>());
}

int main() {
    call_foo<NUM_WIDGETS>();
}
Run Code Online (Sandbox Code Playgroud)

这使用C++ 17倍表达式.如果您没有可用的C++ 17,则可以使用递归模板:

constexpr size_t NUM_WIDGETS = 4;

template <size_t N>
void foo() {
    std::cout << N << '\n';
}

template <size_t N>
void call_foo() {
    foo<N>();
    call_foo<N - 1>();
}

template <>
void call_foo<0>() { }

int main() {
    call_foo<NUM_WIDGETS>();
}
Run Code Online (Sandbox Code Playgroud)