Sobes.tech
Junior — Middle

Can you give an example of using partial specialization of a template in C++?

sobes.tech AI

Answer from AI

Partial specialization of templates in C++ allows defining a class or function template for specific parameter types, leaving other parameters generic. This is useful when you need to change the behavior of a template for certain types without rewriting all variants.

Example of partial specialization of a class template for pointers:

// General template
template<typename T>
struct TypeInfo {
    static const char* name() { return "Unknown"; }
};

// Partial specialization for pointers
template<typename T>
struct TypeInfo<T*> {
    static const char* name() { return "Pointer"; }
};

// Usage
#include <iostream>

int main() {
    std::cout << TypeInfo<int>::name() << std::endl;    // Outputs "Unknown"
    std::cout << TypeInfo<int*>::name() << std::endl;   // Outputs "Pointer"
}
Can you give an example of using partial… - sobes.tech