C++ 템플릿 특수화(Template Specialization)을 이용하여 특정 타입만 허용하는 함수 구현

소스 코드에서 foo() 함수는 myString과 ccString2 타입만 허용하도록 하여, 다른 타입들이 들어오면 컴파일 오류를 발생하는 예제
#include <iostream>
#include <type_traits>
struct myString {
};
struct ccString1 : public myString {
};
struct ccString2 : public myString {
};
template<typename T>
struct check_type
: std::false_type
{ // determine whether T is type that we want
};
template<>
struct check_type<myString>
: std::true_type
{ // determine whether T is type that we want
};
template<>
struct check_type<ccString2>
: std::true_type
{ // determine whether T is type that we want
};
template <bool, class T = void>
struct enable_if
{};
template <class T>
struct enable_if<true, T>
{
typedef T type;
};
template <class T>
typename enable_if<check_type<T>::value, T>::type
foo(T t)
{
// …
return t;
}
int main()
{
ccString1 str1;
ccString2 str2;
foo<ccString1>(str1);
foo<ccString2>(str2);
return 0;
}

댓글

이 블로그의 인기 게시물

macOS가 갑자기 부팅이 되지 않을 경우 데이터 복구 또는 백업 방법

C++로 프로그래밍할 때 인자 또는 리턴 값으로 std::vector 등 STL 데이터 타입 처리하는 좋은 방법

Git 저장소를 병합하는 방법(How to merge repositories in Git)