好吧,杰西已经提供了一个解决方案,但无论如何我都会把我的留在这里。
// Tests whether the first template argument is equal to at least
// one of the rest of them
// e.g. any_is_same<int, char, bool, int>::value == true
// e.g. any_is_same<int, char, bool, std::string>::value == false
template<typename...>
struct any_is_same;
// Base cases
template<typename T, typename... Types>
struct any_is_same<T, T, Types...> {
enum { value = true };
};
template<typename T>
struct any_is_same<T> {
enum { value = false };
};
// Recursive
template<typename T, typename Head, typename... Tail>
struct any_is_same<T, Head, Tail...> {
enum { value = any_is_same<T, Tail...>::value };
};
// Helper
template<typename T>
struct is_some_char {
enum { value = any_is_same<T, char, signed char, unsigned char>::value };
};
template <typename type, typename std::enable_if<is_some_char<type>::value, int>::type = 0>
void foo(type x)
{
}
any_is_same
如果你假装对其他类型做同样的事情(比如int
/ unsigned int
/ signed int
/...) ,你可以重用类型特征:
template<typename T>
struct is_some_int {
enum { value = any_is_same<T, int, signed int, unsigned int>::value };
};
演示在这里。