3

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. And I want to know how to modify it.

Any reply will be appreciated!

1
  • In C++17, without recursion: template <std::size_t...Inputs> constexpr std::size_t Accumulate<Inputs> = (0 + ... + Inputs);. Commented Jan 24, 2020 at 8:51

1 Answer 1

3

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: i.e. 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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.