Template specialization for multiple types

c++, c++03, templates

Solution

You need your `remap` trait to simply map from input types to output types, and have your `foo<T>(int)` interface function delegate to a `foo_implementation<remap<T>::type>(int)` implementation. i.e.:

template <typename T>
struct remap {
    // Default: Output type is the same as input type.
    typedef T type;
};

template <>
struct remap<char> {
    typedef unsigned char type;
};

template <>
struct remap<signed char> {
    typedef unsigned char type;
};

template <typename T>
void foo_impl(int x);

template <>
void foo_impl<unsigned char>(int x) {
    std::cout << "foo_impl<unsigned char>(" << x << ") called\n";
}

template <typename T>
void foo(int x) {
    foo_impl<typename remap<T>::type>(x);
}

See it live at ideone.com.

That said, it might be realistically simpler to define `foo_char`, `foo_int` and `foo_short` and just call the correct one from client code. `foo<X>()` isn't syntactically much different from `foo_X()`.

Problem

Title is a little ambiguous. Lets say I have a template defined as: ``` template < typename T > void foo ( int x ) ; template <> void foo<char> ( int x ) ; template <> void foo<unsigned char> ( int x ) ; template <> void foo<short> ( int x ) ; ... ``` Internally both `foo<signed>()` and `foo<unsigned>()` do exactly the same thing. The only requirement is that `T` be an 8bit type. I could do this by creating another template to type define a standard type based on size. ``` template < typename T, size_t N = sizeof( T ) > struct remap ; template < typename T, size_t > struct remap< 1 > { typedef unsigned char value; } ... ``` Note, function templates cannot have default parameters. This solution only relocates the problem to another template and also introduces a problem if somebody tried passing a struct type as a parameter. What is the most elegant way to solve this without repeating those function declarations? This is not a C++11 question.

Original source