功能模板的部分专门化的解决方法? [英] A workaround for partial specialization of function template?

查看:130
本文介绍了功能模板的部分专门化的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下metafunction的一个完整的pow(它只是一个例子):

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

如何写这种函数的停止条件?

 模板< int N> 
using int_ = std :: integr_constant< int,N> ;;

class Meta
{
template< int N,typename T> static constexpr T ipow(T x)
{
return ipow< N,T>(x,int_<(N< 0)
}

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;
}
};

我想你想传递 -N


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

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

How to write the stop condition for such a function ?

解决方案

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.

这篇关于功能模板的部分专门化的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆