多种类型的模板专业化

Twi*_*fty 10 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 ) ;
...
Run Code Online (Sandbox Code Playgroud)

内部都foo<signed>()foo<unsigned>()做同样的事情.唯一的要求是T8位类型.

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

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

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

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

这不是C++ 11的问题.

dyp*_*dyp 8

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

// 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);
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是为类别类型(类型特征)专门化类模板:

#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);
}
Run Code Online (Sandbox Code Playgroud)

  • C++11 中添加了@leetNightshade `enable_if`;该问题针对 C++03(另外,我已经使用相同的链接向 OP 添加了评论;) (2认同)

Cas*_*sey 5

您需要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);
}
Run Code Online (Sandbox Code Playgroud)

在ideone.com上实时查看

这就是说,它可能是现实的简单定义foo_charfoo_intfoo_short并调用从客户端代码正确的。foo<X>()在语法上与foo_X()