A workaround for partial specialization of function template?

后端 未结 3 777
不思量自难忘°
不思量自难忘° 2020-12-22 07:53

Consider the following metafunction for an integral pow (it is just an example) :

class Meta
{
    template static constexpr T ipow(         


        
相关标签:
3条回答
  • 2020-12-22 08:13

    A simple version might go like this:

    template <typename T, unsigned int N> struct pow_class
    {
        static constexpr T power(T n) { return n * pow_class<T, N - 1>::power(n); }
    };
    
    template <typename T> struct pow_class<T, 0>
    {
        static constexpr T power(T) { return 1; }
    };
    
    template <unsigned int N, typename T> constexpr T static_power(T n)
    {
        return pow_class<T, N>::power(n);
    }
    

    Usage:

    auto p = static_power<5>(2);  // 32
    
    0 讨论(0)
  • 2020-12-22 08:17

    Anytime you ask yourself "how to simulate partial specialization for functions", you can think "overload, and let partial ordering decide what overload is more specialized".

    template<int N>
    using int_ = std::integral_constant<int, N>;
    
    class Meta
    {
        template<int N, typename T> static constexpr T ipow(T x)
        {
            return ipow<N, T>(x, int_<(N < 0) ? -1 : N>());
        }
    
        template<int N, typename T> static constexpr T ipow(T x, int_<-1>)
        {
            //                             (-N) ??
            return static_cast<T>(1) / ipow<-N>(x, int_<-N>());
        }
    
        template<int N, typename T> static constexpr T ipow(T x, int_<N>)
        {
            return x * ipow<N-1>(x, int_<N-1>());
        }
    
        template<int N, typename T> static constexpr T ipow(T x, int_<0>)
        {
            return 1;
        }
    };
    

    I think you wanted to pass -N instead of N at the comment-marked position.

    0 讨论(0)
  • 2020-12-22 08:27

    Just use static members in a class template and specialize the class template. You might want to create a forwarding function template for convenience, though.

    0 讨论(0)
提交回复
热议问题