A workaround for partial specialization of function template?

后端 未结 3 780
不思量自难忘°
不思量自难忘° 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: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
    using int_ = std::integral_constant;
    
    class Meta
    {
        template static constexpr T ipow(T x)
        {
            return ipow(x, int_<(N < 0) ? -1 : N>());
        }
    
        template static constexpr T ipow(T x, int_<-1>)
        {
            //                             (-N) ??
            return static_cast(1) / ipow<-N>(x, int_<-N>());
        }
    
        template static constexpr T ipow(T x, int_)
        {
            return x * ipow(x, int_());
        }
    
        template 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.

提交回复
热议问题