How do I use template specialization and partial specialization?

Template specialization and partial specialization are powerful features of C++ that allow developers to create different implementations of template classes or functions based on specific types. Template specialization enables you to define a specific implementation of a template for a particular type, while partial specialization allows for more flexible matching of types based on certain characteristics.

C++, template specialization, partial specialization, template programming, C++ templates, generic programming
This content explains how C++ template specialization and partial specialization work, with examples to illustrate their usage.

// Full template specialization
template 
class Calculator {
public:
    T add(T a, T b) {
        return a + b;
    }
};

// Specialization for `const char*`
template <>
class Calculator {
public:
    const char* add(const char* a, const char* b) {
        // In a real scenario, a string concatenation function would be used
        return "String addition not supported";
    }
};

// Partial specialization for pointer types
template 
class Calculator {
public:
    T* add(T* a, T* b) {
        return *a + *b;
    }
};

int main() {
    Calculator intCalc;
    std::cout << intCalc.add(3, 4) << std::endl; // Outputs 7

    Calculator strCalc;
    std::cout << strCalc.add("Hello", "World") << std::endl; // Outputs "String addition not supported"

    int a = 2, b = 3;
    Calculator ptrCalc;
    std::cout << ptrCalc.add(&a, &b) << std::endl; // Outputs 5
}
    

C++ template specialization partial specialization template programming C++ templates generic programming