C++ Class Template Specialization

Sort by

recency

|

127 Discussions

|

  • + 0 comments

    Template Specialization is a powerful feature to tailor class or function behavior for specific data types while maintaining a general interface for others. Betguru

  • + 0 comments

    C++ Class Template Specialization is a powerful feature that allows you to define custom behavior for specific data types while still leveraging the flexibility of templates. Gold365 com Login

  • + 0 comments

    Here is C++ Class template specialization solution - https://programmingoneonone.com/hackerrank-cpp-class-templates-problem-solution.html

  • + 0 comments

    include

    using namespace std; enum class Fruit { apple, orange, pear }; enum class Color { red, green, orange };

    template struct Traits;

    template <> struct Traits { static string name(int index) { switch (index) { case 0: return "red"; case 1: return "green"; case 2: return "orange"; default: return "unknown"; } } };

    template <> struct Traits { static string name(int index ) { switch (index) { case 0: return "apple"; case 1: return "orange"; case 2: return "pear"; default: return "unknown"; } } };

    int main() { int t = 0; std::cin >> t;

    for (int i=0; i!=t; ++i) {
        int index1; std::cin >> index1;
        int index2; std::cin >> index2;
        cout << Traits<Color>::name(index1) << " ";
        cout << Traits<Fruit>::name(index2) << "\n";
    }
    

    }

  • + 0 comments

    // We can represent enums like numbers

    template <>
    struct Traits<Color> {
        static string name(int index) {
            switch (index) {
                case 0: return "red";
                case 1: return "green";
                case 2: return "orange";
                default: return "unknown";
            }
        }
    };
    
    // Specialization for Fruit
    template <>
    struct Traits<Fruit> {
        static string name(int index ) {
            switch (index) {
                case 0: return "apple";
                case 1: return "orange";
                case 2: return "pear";
                default: return "unknown";
            }
        }
    };