Implementing a function that accepts only the user defined types in using the template specialization of C++.


A foo() in below source code will be accepted only the two types like myString and String2, but other types will occur an errors on compile time.
#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)