728x90
class template specialization을 처음 써봤다.
Template 변수로 설정해서 모든 타입에 대해서만 사용하는 것이 아니라,
내가 직접 특정 타입을 선택해서 사용 할 수 도 있다.
이때는 template<>를 써주긴 해야 한다.
예를들어 공통 된 template을 위에서 만들고,
특정 color와 fruit이라는 enum을 위한 특별한 template을 만들었다.
#include <iostream>
using namespace std;
enum class Fruit { apple, orange, pear };
enum class Color { red, green, orange };
template <typename T> struct Traits;
// Define specializations for the Traits class template here.
template <>
struct Traits<Fruit>{
static string name(int idx)
{
switch(idx)
{
case 0:
return "apple";
case 1:
return "orange";
case 2:
return "pear";
default:
return "unknown";
}
}
};
template <>
struct Traits<Color>{
static string name(int idx)
{
switch(idx)
{
case 0:
return "red";
case 1:
return "green";
case 2:
return "orange";
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";
}
}
728x90
'개발 공부 > 알고리즘' 카테고리의 다른 글
HackerRank, C++, Bit Array (0) | 2022.11.10 |
---|---|
HackerRank, C++, C++ Variadics (0) | 2022.11.08 |
HackerRank, c++, Attending Workshops (1) | 2022.11.05 |
HackerRank, c++, Operator Overloading (0) | 2022.11.05 |
HackerRank, c++, Magic Spells (1) | 2022.11.04 |