簡體   English   中英

解決部分功能模板專業化問題?

[英]A workaround for partial specialization of function template?

考慮下面的元函數用於整數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<T>(1)/ipow<N>(x)) 
                                  : (1))
    }
};

如何編寫此類功能的停止條件?

每當您問自己“如何模擬函數的部分專用化”時,您都可以考慮“過載,並讓部分排序決定哪種過載更特殊”。

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

我認為您想在注釋位置傳遞-N而不是N

一個簡單的版本可能是這樣的:

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

用法:

auto p = static_power<5>(2);  // 32

只需在類模板中使用static成員並專門化類模板即可。 但是,為方便起見,您可能需要創建轉發功能模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM