多种类型的模板专业化

时间:2013-07-13 05:41:46

标签: c++ templates c++03

标题有点含糊不清。

假设我将模板定义为:

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 ) ;
...

内部foo<signed>()foo<unsigned>()完全相同。唯一的要求是T是8位类型。

我可以通过创建另一个模板来定义基于大小的标准类型。

template < typename T, size_t N = sizeof( T ) > struct remap ;
template < typename T, size_t > struct remap< 1 >
{
    typedef unsigned char value;
}
...

注意,功能模板不能有默认参数。此解决方案仅将问题重定位到另一个模板,如果有人尝试将结构类型作为参数传递,则会引入问题。

在不重复这些函数声明的情况下解决此问题的最优雅方法是什么?

这不是C ++ 11的问题。

2 个答案:

答案 0 :(得分:7)

一种可能性是一次为多种类型专门化一个类模板:

// 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);
}

答案 1 :(得分:4)

您需要remap特征来简单地从输入类型映射到输出类型,并将foo<T>(int)接口函数委托给foo_implementation<remap<T>::type>(int)实现。即:

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

也就是说,定义foo_charfoo_intfoo_short并从客户端代码中调用正确的方法可能更为简单。 foo<X>()在语法上与foo_X()没有太大区别。