繁体   English   中英

多种类型的模板专业化

[英]Template specialization for multiple types

标题有点含糊。

假设我有一个模板定义为:

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 问题。

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

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

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

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

在 ideone.com 上实时查看

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM