簡體   English   中英

需要額外模板參數的類型的函數的部分模板專業化

[英]Partial template specialization of a function for a type which needs additional template parameters

我有一個內部包含數組的類型。 我需要一個函數,該函數返回A或1(如果類型不是A)中的數組成員數。

這是代碼:

#include <cstdio>
template<typename T, unsigned n>
struct A
{
    T values[n];
};
template<typename T>
unsigned count_components()
{
    return 1;//all types except 'A' should have 1 component
}
template<typename T, unsigned n>
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
{
    return n;
}

int main()
{
    printf("%d\n", count_components<A<float, 4> >());//should be 4
    printf("%d\n", count_components<float>());//should be 1
    return 0;
}

G ++錯誤:

test.cpp:13:37: error: function template partial specialization ”count_components<A<T, n> >” is not allowed
unsigned count_components<A<T, n> >()//specialize count_components for 'A'
                                    ^

功能不能部分專門化。 相反,您可以使用可以部分專門化的類:

#include <cstdio>
template<typename T, unsigned n>
struct A
{
    T values[n];
};

template<typename T>
struct component_counter
{
    static unsigned count()
    {
        return 1;
    }
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
    static unsigned count()
    {
        return n;
    }
};
int main()
{
    printf("%d\n", component_counter<A<float, 4> >::count());//should be 4
    printf("%d\n", component_counter<float>::count());//should be 1
    return 0;
}

在這種情況下,count()實際上根本不必是一個函數! 您可以這樣做:

#include <cstdio>
template<typename T, unsigned n>
struct A
{
    T values[n];
};

template<typename T>
struct component_counter
{
    static const unsigned count=1;
};
template<typename T, unsigned n>
struct component_counter<A<T, n> >
{
    static const unsigned count=n;
};
int main()
{
    printf("%d\n", component_counter<A<float, 4> >::count);//should be 4
    printf("%d\n", component_counter<float>::count);//should be 1
    return 0;
}

更少的代碼。 需要注意的是,計數必須是不可或缺的類型才能起作用。

當我有函數時,我更喜歡保留函數(這對成員函數更有利,因為您仍然可以訪問*this )。

template<typename T, unsigned n>
unsigned count_components_switch(boost::mpl::identity<A<T, n>>)
{
    return n;
}

template<typename T>
unsigned count_components_switch(boost::mpl::identity<T>)
{
    return 1;
}

template<typename T>
unsigned count_components()
{
    return (count_components_switch)(boost::mpl::identity<T>());
}

暫無
暫無

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

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