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

时间:2014-03-08 11:23:15

标签: c++ templates template-specialization

我有一个内部包含数组的类型。我需要一个函数,如果类型不是A,则返回A或1中数组成员的数量。

以下是代码:

#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'
                                    ^

2 个答案:

答案 0 :(得分:1)

部分功能无法专业化。相反,您可以使用可以部分专业化的类:

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

哪个代码少。需要注意的是,计数必须是一种不可或缺的类型。

答案 1 :(得分:1)

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