Write me a program in C++ to compute the factorial of a number at compile time, using…
- User
Write me a program in C++ to compute the factorial of a number at compile time, using only C++03
- Assistant
Here's a program in C++ that computes the factorial of a number at compile time using only C++03 features:
#include
template struct Factorial { enum { value = N * Factorial<N - 1>::value }; };
template<> struct Factorial<0> { enum { value = 1 }; };
int main() { std::cout << Factorial<5>::value << std::endl; return 0; } This program uses a recursive template structure to calculate the factorial. The Factorial template has a specialization for the case where N is 0, with a value of 1. The general template calculates N factorial by multiplying N with (N - 1) factorial, which is computed by recursively instantiating the Factorial template with N - 1.
The calculation is performed at compile-time, so there is no runtime overhead. The final result is stored as a constant in the program, so it can be easily accessed.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →