C++11: Template Function Specialization for Integer Types

后端 未结 5 1516
挽巷
挽巷 2020-12-04 19:52

Suppose I have a template function:

template
void f(T t)
{
    ...
}

and I want to write a specialization for all primiti

5条回答
  •  甜味超标
    2020-12-04 20:24

    Use SFINAE

    // For all types except integral types:
    template
    typename std::enable_if::value>::type f(T t)
    {
        // ...
    }
    
    // For integral types only:
    template
    typename std::enable_if::value>::type f(T t)
    {
        // ...
    }
    

    Note that you will have to include the full std::enable_if return value even for the declaration.

    C++17 update:

    // For all types except integral types:
    template
    std::enable_if_t> f(T t)
    {
        // ...
    }
    
    // For integral types only:
    template
    std::enable_if_t> f(T t)
    {
        // ...
    }
    

提交回复
热议问题