Template specialization for multiple types

前端 未结 2 947
日久生厌
日久生厌 2021-02-05 17:13

Title is a little ambiguous.

Lets say I have a template defined as:

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

        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 17:34

    One possibility is to specialize a class template for multiple types at once:

    // from: http://en.cppreference.com/w/cpp/types/enable_if
        template
        struct enable_if {};
    
        template
        struct enable_if { typedef T type; };
    
    template < typename A, typename B >
    struct is_same
    {
        static const bool value = false;
    };
    template < typename A >
    struct is_same
    {
        static const bool value = true;
    };
    
    
    template < typename T, typename dummy = T >
    struct remap;
    
    template < typename T >
    struct remap
    <
        T,
        typename enable_if<    is_same::value
                            || is_same::value, T >::type
    >
    {
        void foo(int);
    };
    
    
    int main()
    {
        remap s;
        s.foo(42);
    }
    

    Another possibility is to specialize a class template for categories of types (type traits):

    #include 
    
    template < typename T >
    struct is_integer
    {
        static const bool value = false;
    };
    template<> struct is_integer { static const bool value = true; };
    template<> struct is_integer { 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::value, T>::type
        , 1 // assuming your byte has 8 bits
    >
    {
        void foo(int);
    };
    
    
    int main()
    {
        remap s;
        s.foo(42);
    }
    

提交回复
热议问题