对于需要其他模板参数的类型函数的部分模板专业化

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

本文关键字:函数 专业化 类型 参数 于需 其他      更新时间:2023-10-16

i具有内部包含数组的类型。我需要一个函数,如果类型不是。

这是代码:

#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("%dn", count_components<A<float, 4> >());//should be 4
    printf("%dn", 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'
                                    ^

当我有功能时,我更喜欢留下功能(这对成员函数更有益,因为您仍然可以访问*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>());
}

函数不能部分专业。相反,您可以使用可以部分专业化的类:

#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("%dn", component_counter<A<float, 4> >::count());//should be 4
    printf("%dn", 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("%dn", component_counter<A<float, 4> >::count);//should be 4
    printf("%dn", component_counter<float>::count);//should be 1
    return 0;
}

这是较少的代码。注意的是,计数必须是一种积分类型才能使其起作用。