How to specialize a template function for enum, and specific type?

前端 未结 2 912
终归单人心
终归单人心 2021-01-14 10:40

I currently have a function:

template 
bool func(T &t, int x)
{
    // do stuff...
}

However I would like to have thr

2条回答
  •  我在风中等你
    2021-01-14 11:14

    Turn out the comment about overload into answer:

    // For enum
    template
    typename std::enable_if::value, bool>::type
    func(T& t, int x);
    
    // for unsigned char
    bool func(unsigned char& t, int x);
    
    // for other
    template
    typename std::enable_if::value, bool>::type
    func(T& t, int x);
    

    Live example

    An alternative is to use specialization for unsigned char:

    // for other
    template
    typename std::enable_if::value, bool>::type
    func(T& t, int x);
    
    // specialization for unsigned char
    template <>
    bool func(unsigned char& t, int x);
    

    Live example

提交回复
热议问题