Template recursion stops after 7 recursions (c++) [closed]

4 weeks ago 16
ARTICLE AD BOX

I have devised the following code, not only to solve a problem but also as a practise example of template recursion for future projects. The intention of the code is to make a version of std::max() that allows one to input an arbitrarily large number of arguments.

(compiled in c++ 23 using g++, MinGW-W64 x86_64, version 13.1.0, on a Windows 11 operating system).

#include <iostream> #include <cmath> // base cases template<typename T1, typename T2, typename... Args_a> auto multi_max(T1 first, T2 second, Args_a... args_a) { if constexpr (sizeof...(args_a) == 0) { return 0; } if constexpr(sizeof...(args_a) == 1) { return static_cast <double> (first); } if constexpr(sizeof...(args_a) == 2) { return static_cast <double> (std::max(first, second)); } else { return static_cast <double> (multi_max(std::max(first, second) , (args_a)...)); } } // recursion code template<typename ...Args_a> auto multi_max(Args_a... args_a) { auto answer = multi_max(args_a...); return static_cast <double> (answer); }

Testing this with the following main() function, I get the answer 110:

// printing result, test 1 int main() { std::cout << multi_max(1, 3, 5, 7, 3, 99, 110, 883, 101); return 0; }

And yet with the following main(), I get the number 883:

// printing result, test 2 int main() { std::cout << multi_max(1, 3, 883, 5, 6, 2, 4, 999, 101); return 0; }

The pattern seems to be that it doesn't read past the seventh argument.

Is this a simple issue of needing a bigger stack for the recursion (thinking of recursion as it occurs in stack-based languages like Prolog), or is there something to fix in how I wrote the code?

I have seen a similar question on Stack Overflow regarding recursion in Python, but a similar query does not seem to exist for c++ (unless I need to look harder to find it?).

Read Entire Article