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.
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; | |
} |
댓글
댓글 쓰기