템플릿 부분 특수화 (Templates Partial Specialization)
- 템플릿에서 여러 파라미터를 받을 때, 특정 파라미터만 특수화할 수 있다.
예제
일반 함수 템플릿 부분 특수화
#include <iostream>
using namespace std;
template <typename T, int size>
class StaticArray
{
private:
T array_[size];
public:
T* getArray() { return array_; }
T& operator[](int index)
{
return array_[index];
}
};
template <typename T, int size>
void print(StaticArray<T, size>& array)
{
for (int count = 0; count < size; ++count)
cout << array[count] << ' ';
cout << endl;
}
template <int size>
void print(StaticArray<char, size>& array)
{
for (int count = 0; count < size; ++count)
cout << array[count];
cout << endl;
}
int main()
{
StaticArray<int, 4> int4;
int4[0] = 1;
int4[1] = 2;
int4[2] = 3;
int4[3] = 4;
print(int4);
StaticArray<char, 14> char14;
strcpy_s(char14.getArray(), 14, "Hello, World!");
print(char14);
}
/* stdout
1 2 3 4
Hello, World!
*/
템플릿 클래스의 멤버 함수 부분 특수화
상속을 이용한다.
#include <iostream>
using namespace std;
template <typename T, int size>
class StaticArray_BASE
{
private:
T array_[size];
public:
T* getArray() { return array_; }
T& operator[](int index)
{
return array_[index];
}
void print()
{
for (int count = 0; count < size; ++count)
cout << (*this)[count] << ' ';
cout << endl;
}
};
template <typename T, int size>
class StaticArray : public StaticArray_BASE<T, size>
{
};
template <int size>
class StaticArray<char, size> : public StaticArray_BASE<char, size>
{
public:
void print()
{
for (int count = 0; count < size; ++count)
cout << (*this)[count];
cout << endl;
}
};
int main()
{
StaticArray<int, 4> int4;
int4[0] = 1;
int4[1] = 2;
int4[2] = 3;
int4[3] = 4;
int4.print();
StaticArray<char, 14> char14;
strcpy_s(char14.getArray(), 14, "Hello, World!");
char14.print();
}
/* stdout
1 2 3 4
Hello, World!
*/