Template specialization for multiple types

前端 未结 2 939
日久生厌
日久生厌 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:47

    You need your remap trait to simply map from input types to output types, and have your foo(int) interface function delegate to a foo_implementation::type>(int) implementation. i.e.:

    template 
    struct remap {
        // Default: Output type is the same as input type.
        typedef T type;
    };
    
    template <>
    struct remap {
        typedef unsigned char type;
    };
    
    template <>
    struct remap {
        typedef unsigned char type;
    };
    
    template 
    void foo_impl(int x);
    
    template <>
    void foo_impl(int x) {
        std::cout << "foo_impl(" << x << ") called\n";
    }
    
    template 
    void foo(int x) {
        foo_impl::type>(x);
    }
    

    See it live at ideone.com.

    That said, it might be realistically simpler to define foo_char, foo_int and foo_short and just call the correct one from client code. foo() isn't syntactically much different from foo_X().

提交回复
热议问题