Appearance
Templates & Type Deduction
Templates are the foundation of generic programming in C++. They allow you to write code that works with multiple types without duplicating the implementation. Internally, C++ achieves this by generating different versions of the template for each type. Let's consider a simple example:
cpp
template<typename T>
T add_values(T a, T b) {
return a + b;
}
int result1 = add_values(10, 20); // T deduced as int
double result2 = add_values(3.14, 2.71); // T deduced as double
std::string result3 = add_values(std::string("hello"), std::string(" world")); // T deduced as std::stringThe above function can be used with any type that supports the + operator. Unlike languages like Java, nothing is generated at run time. Instead, the compiler generates a different version of the function for each type. So for the above example, the compiler will generate three functions like this:
cpp
int add_values(int a, int b) {
return a + b;
}
double add_values(double a, double b) {
return a + b;
}
std::string add_values(std::string a, std::string b) {
return a + b;
}If you don't use the template, no machine code is ever generated. Because the compiler knows which function to call at compile time, there is no runtime overhead for using templates.
Class templates and Non-Type Template Parameters
You can also specify template parameters on classes to introduce generic types. Additionally, you can also specify non-type template parameters to pass compile time constants. For example:
cpp
template<typename T, size_t N>
class Array {
T data[N];
public:
T& operator(size_t index) { return data[index]; }
const T& operator(size_t index) const { return data[index]; }
};
// Usage
Array<int, 10> int_array;
Array<double, 5> double_array;Template Specialization
You can also specialize templates to provide different implementations for specific types. For example:
cpp
template<typename T>
T absolute(T value) {
return (value < 0) ? -value : value;
}
// Specialization for int
template<>
int absolute<int>(int value) {
return abs(value); // Use std::abs for int
}Your Task
Your task would be to implement a class template called factorial that computes the factorial of an integral template parameter at compile time. It should be usable like this:
cpp
const int result = factorial<5>::value; // 120Hint: You can use template specialization to provide the base case for the factorial.
Implement a class template called factorial that computes the factorial of an integral template parameter at compile time. It should be usable like: const int result = factorial<5>::value; // 120
cpp
// TODO: Implement a class template called factorial that computes the factorial
// of an integral template parameter at compile time.
// Your implementation here
template<unsigned int N>
struct factorial;