본문 바로가기
Leaning/C++

[HackerRank] C++ Class Template Specialization

by ksw8596 2024. 10. 17.
#include <iostream>
#include <vector>
#include <deque> 
#include <string>
#include <sstream>
#include <exception>

using namespace std;

enum class fruit { apple, orange, pear };
enum class color { red, green, orange };

//templat -> 자료형을 만듦
template <typename t> struct traits;

// define specializations for the traits class template here.
//템플릿 특수화 : 위 선언된 template를 다른 형식? 으로 쓸 경우 사용
template <>
struct traits<color>
{
    static string name(int index)
    {
        //static_cast<바꾸는 타입>(대상) enum의 값을 받아올 수 있다. (안전하지 않을 수 있음)
        switch (static_cast<fruit>(index))
        {
        case fruit::apple:
            return "apple";
            break;
        case fruit::orange:
            return "orange";
            break;
        case fruit::pear:
            return "pear";
            break;
        default:
            return "unknown";
            break;
        }
    }

};

template <> struct traits<fruit>
{
    static string name(int index)
    {
        switch (static_cast<color>(index))
        {
        case color::red:
            return "red";
            break;
        case color::green:
            return "green";
            break;
        case color::orange:
            return "orange";
            break;
        default:
            return "unknown";
            break;
        }
    }
};


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

    for (int i = 0; i != t; ++i) {
        int index1; std::cin >> index1; //1
        int index2; std::cin >> index2; //0
        cout << traits<color>::name(index1) << " ";
        cout << traits<fruit>::name(index2) << "\n";
    }
}

https://en.cppreference.com/w/cpp/language/static_cast

 

static_cast conversion - cppreference.com

Converts between types using a combination of implicit and user-defined conversions. [edit] Syntax static_cast (expression ) Returns a value of type target-type. [edit] Explanation Only the following conversions can be done with static_cast, except wh

en.cppreference.com

'Leaning > C++' 카테고리의 다른 글

[Hackerrank] Vector-Erase  (0) 2024.11.04
[Hackerrank] Vector-Sort  (0) 2024.11.04
DFS(깊이 우선 탐색), BFS(너비 우선 탐색)  (0) 2024.10.25
C++ 자료구조(STL)  (0) 2024.10.24
[HackerRank] Hotel Prices  (0) 2024.10.17