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.
// 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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?