C++ 템플릿 특수화(Template Specialization)을 이용하여 특정 타입만 허용하는 함수 구현
소스 코드에서 foo() 함수는 myString과 ccString2 타입만 허용하도록 하여, 다른 타입들이 들어오면 컴파일 오류를 발생하는 예제
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
댓글
댓글 쓰기