一种可能性是一次为多种类型专门化一个类模板:
// from: http://en.cppreference.com/w/cpp/types/enable_if
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { typedef T type; };
template < typename A, typename B >
struct is_same
{
static const bool value = false;
};
template < typename A >
struct is_same<A, A>
{
static const bool value = true;
};
template < typename T, typename dummy = T >
struct remap;
template < typename T >
struct remap
<
T,
typename enable_if< is_same<T, unsigned char>::value
|| is_same<T, signed char>::value, T >::type
>
{
void foo(int);
};
int main()
{
remap<signed char> s;
s.foo(42);
}
另一种可能性是为类型的类别(类型特征)专门化一个类模板:
#include <cstddef>
template < typename T >
struct is_integer
{
static const bool value = false;
};
template<> struct is_integer<signed char> { static const bool value = true; };
template<> struct is_integer<unsigned char> { static const bool value = true; };
template < typename T, typename dummy = T, std::size_t S = sizeof(T) >
struct remap;
template < typename T >
struct remap
<
T
, typename enable_if<is_integer<T>::value, T>::type
, 1 // assuming your byte has 8 bits
>
{
void foo(int);
};
int main()
{
remap<signed char> s;
s.foo(42);
}