简体   繁体   English

c ++模板用递归实现循环

[英]c++ template implement loop with recursion

I'm trying to write a meta function with recursion.我正在尝试用递归编写一个元函数。 The inputs are variadic integers, and the output should be the sum of the inputs.输入是可变整数,输出应该是输入的总和。

My code like follows:我的代码如下:

template <size_t curInput, size_t...Inputs>
constexpr size_t Accumulate = curInput + Accumulate<Inputs...>;

// template specialization
template <size_t...Inputs>
constexpr size_t Accumulate<Inputs> = 0;

int main(int argc, char *argv[]) {
  constexpr size_t res1 = Accumulate<1>;
  constexpr size_t res2 = Accumulate<1, 2, 3, 4, 5>;
  return 0;
}

With the test in main() , the res1 is 0, and res2 is 10. It seems like treat the last integer as 0, I don't understand why this happened.通过main()的测试, res1为 0, res2为 10。似乎将最后一个整数视为 0,我不明白为什么会发生这种情况。 And I want to know how to modify it.我想知道如何修改它。

Any reply will be appreciated!任何答复将不胜感激!

Your recursive template requires at least one parameter, and plucks off the first one, then recurses.您的递归模板至少需要一个参数,然后去掉第一个参数,然后递归。 Therefore, your specialization should be for the case where there is exactly one template parameter: ie the base case.因此,您的专业化应该针对只有一个模板参数的情况:即基本情况。

#include <iostream>

template <size_t curInput, size_t...Inputs>
constexpr size_t Accumulate = curInput + Accumulate<Inputs...>;

// template specialization
template <size_t curInput>
constexpr size_t Accumulate<curInput> = curInput;

int main(int argc, char *argv[]) {
  constexpr size_t res1 = Accumulate<1>;
  constexpr size_t res2 = Accumulate<1, 2, 3, 4, 5>;

  std::cout << res1 << " " << res2 << std::endl;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM