14

标题有点模棱两可。

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

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>()做完全相同的事情。唯一的要求是T8 位类型。

我可以通过创建另一个模板来键入基于大小定义标准类型来做到这一点。

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

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

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

这不是 C++11 问题。

4

2 回答 2

12

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

// 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);
}
于 2013-07-13T06:16:03.813 回答
7

您需要您的remaptrait 简单地从输入类型映射到输出类型,并将您的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_int并且foo_short只需从客户端代码中调用正确的代码。foo<X>()在语法上与 . 没有太大区别foo_X()

于 2013-07-13T06:31:03.323 回答